post 方法
/**
* Post 方式
*
* @param url
* 网址
* @param paramsArray
* 参数
* @param values
* 值
* @param charset
* 编码,例如:UTF-8、GBK
* @return
*/
public static String postUrl(String url, String[] paramsArray,
String[] values, String charset) {
String returnConnection = null;
// 封装数据
Map<String, String> parmas = new HashMap<String, String>();
int paramsArrayLength = paramsArray.length;
int valuesLength = values.length;
if (paramsArrayLength == valuesLength) {
for (int i = 0; i < paramsArrayLength; i++) {
System.out.println("paramsArray = " + paramsArray[i] +
", value = " + values[i]);
parmas.put(paramsArray[i], values[i]);
}
DefaultHttpClient client = new DefaultHttpClient();// http客户端
HttpPost httpPost = new HttpPost(url);
List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
if (parmas != null) {
Set<String> keys = parmas.keySet();
for (Iterator<String> i = keys.iterator(); i.hasNext();) {
String key = (String) i.next();
pairs.add(new BasicNameValuePair(key, parmas.get(key)));
System.out.println("key = " + key + ", value = "
+ parmas.get(key));
}
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(
pairs, charset);
// 将POST数据放入HTTP请求
httpPost.setEntity(p_entity);
// 发出实际的HTTP POST请求
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("错误代码: " + statusCode);
} else {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
returnConnection = changeInputStream(content);
// returnConnection = content.toString();//
// changeInputStream(content);
System.out.println("结果2:" + returnConnection);
}
} catch (IllegalStateException e) {
e.printStackTrace();
System.out.println("出错1:" + e.getStackTrace());
} catch (IOException e) {
e.printStackTrace();
System.out.println("出错2:" + e.getStackTrace());
}
}
} else {
System.out.println("出错3:参数不对");
}
return returnConnection;
}
streamToString方法
private static String changeInputStream(InputStream inputStream) {
// TODO Auto-generated method stub
String jsonString = "";
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = 0;
byte[] data = new byte[1024];
try {
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
jsonString = new String(outputStream.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonString;
}