HttpClient HttpPost请求

来源:互联网 发布:双击python文件闪退 编辑:程序博客网 时间:2024/04/29 21:41
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


import android.util.Log;


public class AndHttpPost {
public static String request(String data, String url) {
try {
// 数据实体
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("isucvip", data));
HttpEntity httpEntity = new UrlEncodedFormEntity(list, "UTF-8");
// 打开一个浏览器
HttpClient httpClient = new DefaultHttpClient();
// 输入地址
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(httpEntity);
// 客户端对象来发送请求
HttpResponse httpResponse = httpClient.execute(httpPost);


int code = httpResponse.getStatusLine().getStatusCode();
if (code == 200) {
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

String result = "";
String line = "";
while (null != (line = reader.readLine())) {
result += line;
}
reader.close();
inputStream.close();
Log.e("AndHttpPost", "result = " + result + " jsonStr = " + data);
return result;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
0 0
原创粉丝点击