您的位置:首页 > 理论基础 > 计算机网络

Android使用HttpURLConnection进行POST请求,向服务器上传数据

2015-12-27 19:45 781 查看
先在清单文件中需要添加权限:

<uses-permission android:name="android.permission.INTERNET"/>


开始使用HttpURLConnection进行POST请求,向服务器上传数据:

(1)定位到要获取资源的网址并打开连接:

URL url = new URL(String urlPath);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();


(2)进行连接设置:

//设置连接超时,2000ms
httpURLConnection.setConnectTimeout(2000);
//设置指定时间内服务器没有返回数据的超时,5000ms
httpURLConnection.setReadTimeout(5000);
//设置允许输出
httpURLConnection.setDoOutput(true);
//设置请求的方式
httpURLConnection.setRequestMethod("POST");


(3)将要传送的数据写入输出流:

PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream());
out.print(timeTag);//写入输出流
out.flush();//立即刷新

out.close();


(4)对响应码进行判断,并获取网络返回的输入流:

int code = httpURLConnection.getResponseCode();
if(code == 200){
InputStream is = httpURLConnection.getInputStream();
//连接服务器后,服务器做出响应返回的数据
String serverResponse = URLDecoder.decode(readInStream(is), "utf-8");

is.close();

//对返回的数据serverResponse进行操作

}


(5)关闭连接:

httpURLConnection.disconnect();


一个向服务器上传Json数据包的例子:

/**
* 将Json对象上传服务器
* @param url
* @param jsonObject
* @throws JSONException
*/
private void postJsonToServer(URL url, JSONObject jsonObject ) throws JSONException {

//把JSON数据转换成String类型使用输出流向服务器写
try {
String str = "user="+ URLEncoder.encode(URLEncoder.encode(String.valueOf(jsonObject), "UTF-8"),"UTF-8");

try {
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setDoOutput(true);//设置允许输出
httpURLConnection.setRequestMethod("POST");//设置请求的方式
httpURLConnection.setRequestProperty("ser-Agent", "Fiddler");

//把上面访问方式改为异步操作,就不会出现 android.os.NetworkOnMainThreadException异常
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream());
out.print(str);//写入输出流
out.flush();//立即刷新

out.close();

int code = httpURLConnection.getResponseCode();
if(code == 200 && ((url.toString()).equals(httpURLConnection.getURL().toString()))){
//获取服务器响应后返回的数据
InputStream is = httpURLConnection.getInputStream();
String successResponse = URLDecoder.decode(readInStream(is), "utf-8");
is.close();

if(SUCCESS_RESPONSE.equals(successResponse)){

//上传成功
}

} else{

//上传失败
}

}catch (ConnectException e){
e.printStackTrace();
}

catch (SocketTimeoutException e){
e.printStackTrace();

catch (IOException e) {
e.printStackTrace();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: