http get/post请求及json解析
·
public static String httpRequest(String url, String jsonString, String codeType) {
StringBuffer result = new StringBuffer();
log.debug("http请求:" + url);
org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpPost post = new HttpPost(url);
StringEntity s;
HttpResponse res = null;
try {
if(StringUtils.isNotEmpty(jsonString)) {
log.debug("post请求串:" + jsonString);
s = new StringEntity(jsonString);
s.setContentEncoding(codeType);
s.setContentType("application/json");
post.setEntity(s);
res = httpClient.execute(post);
} else {
res = httpClient.execute(get);
}
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
JSONTokener tokener = new JSONTokener(new InputStreamReader(entity.getContent(), codeType));
char c = '\0';
while ((c = tokener.next()) != '\0') {
result.append(c);
}
log.debug("http响应:" + result.toString());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (org.json.JSONException e) {
e.printStackTrace();
}
return result.toString();
StringBuffer result = new StringBuffer();
log.debug("http请求:" + url);
org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpPost post = new HttpPost(url);
StringEntity s;
HttpResponse res = null;
try {
if(StringUtils.isNotEmpty(jsonString)) {
log.debug("post请求串:" + jsonString);
s = new StringEntity(jsonString);
s.setContentEncoding(codeType);
s.setContentType("application/json");
post.setEntity(s);
res = httpClient.execute(post);
} else {
res = httpClient.execute(get);
}
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
JSONTokener tokener = new JSONTokener(new InputStreamReader(entity.getContent(), codeType));
char c = '\0';
while ((c = tokener.next()) != '\0') {
result.append(c);
}
log.debug("http响应:" + result.toString());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (org.json.JSONException e) {
e.printStackTrace();
}
return result.toString();
jar包:json-lib-2.4,commons-httpClient-3.1
新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐



所有评论(0)