import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import android.util.Log;
public class HttpRequest {
private DefaultHttpClient httpClient;
private HttpContext localContext;
private String ret;
private HttpResponse response = null;
private HttpPost httpPost = null;
private HttpGet httpGet = null;
public HttpRequest() {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if (httpClient != null) {
System.out.println("Abort.");
httpPost.abort();
}
} catch (Exception e) {
System.out.println("Your App Name Here" + e);
}
}
public String sendPost(String url, String data) {
return sendPost(url, data, null);
}
public String sendJSONPost(String url, JSONObject data) {
return sendPost(url, data.toString(), "application/json");
}
public String sendPost(String url, String data, String contentType) {
ret = null;
httpClient.getParams().setParameter(
ClientPNames.COOKIE_POLICY,
CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
Log.d("Your App Name Here", "Setting httpPost headers");
httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q = 0.9,text / plain;q = 0.8,image / png,*/*;q=0.5");
if (contentType != null) {
httpPost.setHeader("Content-Type", contentType);
} else {
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try {
tmp = new StringEntity(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Your App Name Here", "HttpUtils : UnsupportedEncodingException : " + e);
}
httpPost.setEntity(tmp);
Log.d("Your App Name Here", url + "?" + data);
try {
response = httpClient.execute(httpPost, localContext);
if (response != null) {
ret = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
Log.e("Your App Name Here", "HttpUtils: " + e);
}
Log.d("Your App Name Here", "Returning value:" + ret);
return ret;
}
public String sendGet(String url) {
httpGet = new HttpGet(url);
ret = null;
try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Your App Name Here", e.getMessage());
}
//int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
try {
if (response != null) {
ret = EntityUtils.toString(response.getEntity());
}
} catch (IOException e) {
Log.e("Your App Name Here", e.getMessage());
}
return ret;
}
public InputStream getHttpStream(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
throw new IOException("Not an HTTP connection");
}
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception e) {
throw new IOException("Error connecting");
} // end try-catch
return in;
}
}
เอาอย่างนี้น่ะครับ คือว่า เราไม่ต้องสนใจว่า ตัวโปรแกรม มันจะใช้คำสั่งอะไร มีคอนเน็คชัน อะไรบ้าง ขอให้รู้แค่วิธีใช้งานมันก็พอน่ะครับ เพราะมันก็เยอะอยู่ ^^ ถ้าจะอธิบาย
เดี๋ยวค่อยไปหาศึกษาเอาเองน่ะครับ
ผมขออธิบายวิธิใช้เลยแล้วกันครับ
รู้อยู่อย่างแรกว่า อันนี้เป็น class ที่ถูกเขียนสำเร็จรูปไว้ สามารถนำไปใช้งานได้ทันทีน่ะครับ
1. สร้าง object httpRequest ขึ้นมาดังนี้
HttpRequest http = new HttpRequest();
2. เราอยากจะใช้ object นี้ทำหน้าที่อะไร ก็ใช้งานตาม method ที่มีอยู่ครับ ดังนี้
-public String sendPost(String url, String data) {}
หน้าที่คือโพสต์ข้อมูลไปยัง web server โดยมีพารามิเตอร์เป็น url web server กับ data ที่จะส่งไป ดังนี้
String receive = http.sendPost("http://na5cent.blogspot.com", "x=1&y=2&z=3");
ประมาณนี้ครับ ฝั่ง server ก็ post ค่ารับเอา ถ้า server มีอะไรส่งกลับมา ก็จะมาลงอยู่ที่ receive
-public String sendJSONPost(String url, JSONObject data) {}
อันนี้เหมือนข้างบน แต่ข้อมูลที่ส่งไป อยู่ในรูปของ json ครับ
-public String sendPost(String url, String data, String contentType) {}
อันนี้ก็เหมือนอันแรก แค่มีการ set content type ด้วยแค่นั้นเอง
-public String sendGet(String url) {}
อันนี้ทำหน้าที่รับข้อมูลมาจาก server การใช้งาน มีดังนี้
String receive = http.sendGet("http://na5cent.blogspot.com");
- public InputStream getHttpStream(String urlString) throws IOException { }
อันนี้ใช้สำหรับการรับค่าที่เป็น stream มาจาก server เช่นพวก รูปภาพหรือไฟล์ต่างๆ ที่ server ส่งกลับมาในรูปของ stream ครับ วิธีใช้
InputStream receiveStream = null;
try{
receiveStream = http.getHttpStream("http://na5cent.blogspot.com/test.png");
}catch(IOException e){
...
}finally{
...
try{
receiveStream.close();
}catch(IOException e){
...
}
}
-public void abort() {}
ยกเลิกการเชื่อมต่อ วิธีใช้ http.abort();
-public void clearCookies() {}
เคลียร์คุกกี้ครับ วิธีใช้ http.clearCookies();
คิดว่าพอใช้เป็นน่ะครับ
มันก็ยังต้องมีการเขียนปรับปรุงเพิ่มเติมอีกบ้าง แต่ก็พอทำงานได้
เพราะผมเองก็ใช้ในการรับส่งข้อมูลระหว่าง client server(android กับ php) มาแล้ว
ช่วยอธิบายที ครับ งง ๆ
ตอบลบ