80,351
社区成员
发帖
与我相关
我的任务
分享
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "aaa");
jsonObject.put("password", “bbb”);
nameValuePair.add(new BasicNameValuePair("jsonString", jsonObject
.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "aaa");
jsonObject.put("password", “bbb”);
StringEntity entity = new StringEntity(jsona.toString());
httpPost.setEntity(entity);
/**
* 发送Post请求到服务器 ,並返回請求結果
*
* @param params
* 請求參數
* @param encode
* 請求的編碼格式
* @param urlString
* 請求的URL地址
* @return 返回讀取到的字符串
*/
public static String submitPostData(Map<String, String> params,
String encode, String urlString) {
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] data = getRequestData(params, encode).toString().getBytes();// 获得请求体
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) (url)
.openConnection();
httpURLConnection.setConnectTimeout(5000);// 设置连接超时时间
httpURLConnection.setDoInput(true);// 打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true);// 打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST");// 设置以Post方式提交数据
httpURLConnection.setUseCaches(false); // 使用Post方式不能使用缓存
// 设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(data.length));
// 获得输出流,向服务器写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data);
int response = httpURLConnection.getResponseCode(); // 获得服务器的响应码
if (response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
return getResponseResult(inptStream);
}
} catch (IOException e) {
Log.d(TAG, "网络请求连接超时!");
return null;
}
return null;
}
/**
* 封裝請求,請求的參數使用&進行隔開,服務端通過截取&進行解析 例如:請求參數 ("userid",1)
* ("username","admin")-->轉換後的格式爲:userid=1&username=admin
* 如果是其他非英文字符則會自動轉換成UTF-8的格式編碼
*
* @param params
* 請求的參數,鍵/值對應
* @param encode
* 請求編碼
* @return
*/
private static StringBuffer getRequestData(Map<String, String> params,
String encode) {
StringBuffer stringBuffer = new StringBuffer(); // 存储封装好的请求体信息
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1); // 删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
}
里面请求的参数自键-值对应的,是用map或者其它