Android的Post请求:
1、创建HttpPost实例,设置需要请求服务器的url。
2、为创建的HttpPost实例设置参数,参数设置时使用键值对的方式用到NameValuePair类。
3、发起post请求获取返回实例HttpResponse
4、使用EntityUtils对返回值的实体进行处理(可以取得返回的字符串,也可以取得返回的byte数组)
private void getWeather() {
final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定义需要获取的内容来源地址
HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("theCityCode", "2416")); // 添加必须的参数
params.add(new BasicNameValuePair("theUserID",
"23e848cd1c4c4b1ba5d94f70bd414034")); // 添加必须的参数
HttpResponse httpResponse = null;
try {
// 设置httpPost请求参数
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = new DefaultHttpClient().execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
if (code == 200) {
String result = EntityUtils.toString(httpResponse.getEntity());
Log.i(TAG, "code=" + result);
Toast.makeText(UploadTest.this, result, Toast.LENGTH_LONG)
.show();
} else {
Log.i(TAG, "code="
+ httpResponse.getStatusLine().getStatusCode());
Toast.makeText(UploadTest.this, code + "", Toast.LENGTH_LONG)
.show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Java的Post请求:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class JavaPostDemo {
public static void main(String[] args) {
try {
getWeather();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void getWeather() throws Exception {
String theCityCode = "2416";
String theUserID = "23e848cd1c4c4b1ba5d94f70bd414034";
URL url = new URL("http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 提交模式
conn.setConnectTimeout(10000);// 连接超时 单位毫秒
conn.setReadTimeout(2000);// 读取超时 单位毫秒
conn.setDoOutput(true);// 是否输入参数
StringBuffer params = new StringBuffer();
// 表单参数与get形式一样
params.append("theCityCode").append("=").append(theCityCode)
.append("&").append("theUserID").append("=").append(theUserID);
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream = conn.getInputStream();
System.out.println(new String(readInputStream(inStream), "utf-8"));
}
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();// 网页的二进制数据
outStream.close();
inStream.close();
return data;
}
}