方式一:
public String updateRequest(String operation,String phone) {
String strResult = null;
HttpPost httpRequest =new HttpPost(CommonURL.UpdateURL);
List <NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Operation",operation));
params.add(new BasicNameValuePair("Phone",phone));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode()==200){
//取出回应字串
strResult=EntityUtils.toString(httpResponse.getEntity());
Pattern titleP = Pattern.compile("<body>(.*\r\n)*</body>");
Matcher matchedTitle = titleP.matcher(strResult);
Boolean foundTitle = matchedTitle.find();
if(foundTitle){
strResult = matchedTitle.group(1);
}
}else{
Log.e("请求结果:", "请求失败!");
}
}catch(ClientProtocolException e){
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strResult;
}
方式二:
public String sendRequest(JSONObject object,String MyURL) {
String jsonStr=null;
try {
URL url = new URL(MyURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ser-Agent", "Fiddler");
conn.setRequestProperty("Content-Type", "application/json");
conn.setConnectTimeout(5 * 1000);
// 包装并上传数据
OutputStream outputStream = conn.getOutputStream();
outputStream.write(URLEncoder.encode(object.toString(), "UTF-8").getBytes());
// 如果请求响应码是200,则表示成功
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//获取服务器上的数据
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
//解码
jsonStr = URLDecoder.decode(in.readLine(), "UTF-8");
in.close();
conn.disconnect();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SocketTimeoutException e) {
jsonStr = "连接超时";
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}