HttpURLConnection 、HttpPost、Okhttp 等POST方式傳送JSON資料
阿新 • • 發佈:2019-01-11
一、HttpURLConnection Post方式傳送JSON資料
public class GetResult extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... arg0) {
String result = "" ;
URL url = null;
BufferedReader reader = null;
try {
String parma = "{\"name\": \"hah\"}";
url = new URL("url");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true );
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Length", String.valueOf(parma.length()));
connection.setRequestProperty("Content-Type" ,"application/json; charset=UTF-8");
connection.setRequestProperty("accept","application/json");
OutputStream out = connection.getOutputStream();
out.write(parma.getBytes());
out.flush();
out.close();
if (connection.getResponseCode()==200){
reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
result = reader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
@Override
protected void onPostExecute(String re) {
super.onPostExecute(re);
value.setText(re);
}
}
2、HttpPost 傳送json資料
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url");
StringEntity se = new StringEntity("{\"dog\":{\"name\": \"hah\"}}");
httpPost.setEntity(se);
httpPost.setHeader("Content-Type", "application/json");
@SuppressWarnings("deprecation")
HttpResponse httpResponse = httpClient.execute(httpPost);
String str = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
re = JSON.parseObject(str,ModelArrayResult.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3、Okhttp post 傳送JSON
public class HttpUtil {
public static final OkHttpClient client = new OkHttpClient();
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
public static <T> T post(String Url, String postBody, Class<T> clazz) {
T result = null;
Request request = new Request.Builder()
.url(Url)
.post(RequestBody.create(MEDIA_TYPE_JSON,postBody))
.build();
Response response = null;
try {
response = client.newCall(request).execute();
// 此處response.body().string()能用呼叫一次!
String str = response.body().string();
Log.i("ResponseToString",str);
result = JSON.parseObject(str, clazz);
}catch (Exception e){
e.printStackTrace();
}finally {
response.close();
}
return result;
}
}