求助,java用httpclient包,模拟发送json和接受json
若以下回答无法解决问题,邀请你更新回答
推荐于2016-10-02 · 知道合伙人软件行家
Axure夜话
知道合伙人软件行家
向TA提问 私信TA
知道合伙人软件行家
采纳数:1197
获赞数:1344
1992年毕业于太原理工大学,20年IT公司工作经验现任山西誉海和科技有限公司技术总监,老二牛车教育课程总监
向TA提问 私信TA
关注
展开全部
httpclient类库包含了get,post发送数据的相关的方法
参考代码:get方式
String httpUrl = "http://192.168.1.116:8080/AndroidWeb/httpreq.jsp?par=request-get";
HttpGet request = new HttpGet(httpUrl);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String str = EntityUtils.toString(response.getEntity());
tv_rp.setText(str);
} else {
tv_rp.setText("请求错误");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
-------------------------
post方式
String httpUrl = "http://192.168.1.116:8080/AndroidWeb/httpreq.jsp";
HttpPost request = new HttpPost(httpUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("par","request-post"));
try {
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
request.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String str = EntityUtils.toString(response.getEntity());
tv_rp.setText(str);
}else{
tv_rp.setText("请求错误");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
参考代码:get方式
String httpUrl = "http://192.168.1.116:8080/AndroidWeb/httpreq.jsp?par=request-get";
HttpGet request = new HttpGet(httpUrl);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String str = EntityUtils.toString(response.getEntity());
tv_rp.setText(str);
} else {
tv_rp.setText("请求错误");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
-------------------------
post方式
String httpUrl = "http://192.168.1.116:8080/AndroidWeb/httpreq.jsp";
HttpPost request = new HttpPost(httpUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("par","request-post"));
try {
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
request.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String str = EntityUtils.toString(response.getEntity());
tv_rp.setText(str);
}else{
tv_rp.setText("请求错误");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询