httpclient发送字符串 得到字符串怎么直接解析

3029人阅读
JAVAEE(31)
一、读取思路
1.使用InputStream对象构造InputStreamReader
2.使用InputStreamReader对象构造BufferedReader对象
3.构造一个StringBuilder对象,用来接收BufferedReader中的数据
二、源代码
public void test3() throws Exception, IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(&url&);
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
//创建一个输入流对象
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line =
while ((line = reader.readLine()) != null) {
sb.append(line + &\n&);
instream.close();
System.out.println(sb.toString());
//如何从InputStream中读取数据到字符串
//从输入流中读取数据
/*int byteOne = instream.read();
int byteTwo = instream.read();
System.out.println(byteOne);
System.out.println(byteTwo);*/
} finally {
response.close();
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:59652次
排名:千里之外
原创:39篇
转载:13篇
(1)(1)(2)(12)(6)(11)(6)(12)(2)
(window.slotbydup = window.slotbydup || []).push({
id: '4740881',
container: s,
size: '200,200',
display: 'inlay-fix'I have a problem post string to form and read. Problem is they get away but need to do so sophisticated and it was very fast. Absolutely perfect multithreaded or asynchronous. Thank you very for your help.
This is my code.
private static void AsyncDown()
const string url = "http://whois.sk-nic.sk/index.jsp";
const string req = "PREM-0001";
var client = new HttpClient();
var pairs = new List&KeyValuePair&string, string&&
new KeyValuePair&string, string&("text", "PREM-0001")
FormUrlEncodedContent content = new FormUrlEncodedContent(pairs);
HttpResponseMessage response = client.PostAsync("http://whois.sk-nic.sk/index.jsp", content).R
if (response.IsSuccessStatusCode)
HttpContent stream = response.C
Task&string& data = stream.ReadAsStringAsync();
解决方案 Maybe the site has changed since last post but now the request parameter name is whois not text. If this was the case a year ago too that's why it didn't work.
Today site responds to get too, i.e.
Full code with get:
private async Task&string& Get(string code)
using (var client = new HttpClient())
var requestUri = String.Format("http://whois.sk-nic.sk/index.jsp?whois={0}", code);
var data = await client.GetStringAsync(requestUri);
Full code with post:
private async Task&string& Post()
using (var client = new HttpClient())
var postData = new KeyValuePair&string, string&[]
new KeyValuePair&string, string&("whois", "PREM-0001"),
var content = new FormUrlEncodedContent(postData);
var response = await client.PostAsync("http://whois.sk-nic.sk/index.jsp", content);
if (!response.IsSuccessStatusCode)
var message = String.Format("Server returned HTTP error {0}: {1}.", (int)response.StatusCode, response.ReasonPhrase);
throw new InvalidOperationException(message);
var data = await response.Content.ReadAsStringAsync();
Or a parser could be used because I guess extracting the returned values is the final goal:
private void HtmlAgilityPack(string code)
var requestUri = String.Format("http://whois.sk-nic.sk/index.jsp?whois={0}", code);
var request = new HtmlWeb();
var htmlDocument = request.Load(requestUri);
var name = htmlDocument.DocumentNode.SelectSingleNode("/html/body/table[1]/tr[5]/td/table/tr[2]/td[2]").InnerText.Trim();
var organizations = htmlDocument.DocumentNode.SelectSingleNode("/html/body/table[1]/tr[5]/td/table/tr[3]/td[2]").InnerText.Trim();
本文地址: &
我有一个问题后字符串形成和读取。问题是他们离开,但需要做的非常成熟,这是非常快的。绝对完美的多线程或异步的。非常感谢您的帮助。这是我的code。 私有静态无效AsyncDown()
常量字符串URL =“http://whois.sk-nic.sk/index.jsp”;
常量字符串REQ =“preM-0001”;
VAR的客户=新的HttpClient();
对VAR =新名单< KeyValuePair<字符串,字符串>>
新KeyValuePair<字符串,字符串>(“文字”,“preM-0001」)
FormUrlEn codedContent内容=新FormUrlEn codedContent(对);
HTT presponseMessage响应= client.PostAsync(“http://whois.sk-nic.sk/index.jsp”,内容)。结果;
如果(response.IsSuccessStatus code)
HttpContent流= response.C
任务<串GT;数据= stream.ReadAsStringAsync();
} 解决方案 也许自去年后该网站已经改变,但现在请求参数名的whois不是文本。如果这在一年前是太大的情况下,这就是为什么它没有工作。今天现场回应太,即 全部code用GET: 专用异步任务<串GT;获取(字符串code){
使用(VAR的客户=新的HttpClient())
VAR requestUri =的String.Format(“http://whois.sk-nic.sk/index.jsp?whois={0}”,code);
VAR数据=等待client.GetStringAsync(requestUri);
返回的数据;
}} 全部code。与岗位: 专用异步任务<串GT;邮政(){
使用(VAR的客户=新的HttpClient())
VAR POSTDATA =新KeyValuePair<字符串,字符串> []
新KeyValuePair<字符串,字符串>(“域名注册”,“preM-0001”),
VAR内容=新FormUrlEn codedContent(POSTDATA);
VAR响应=等待client.PostAsync(“http://whois.sk-nic.sk/index.jsp”内容);
如果(!response.IsSuccessStatus code)
VAR消息=的String.Format(“服务器返回的HTTP错误{0}:{1}。”(INT)response.Status code,response.ReasonPhrase);
抛出新的InvalidOperationException异常(消息);
VAR数据=等待response.Content.ReadAsStringAsync();
返回的数据;
}} 还是因为我猜提取返回值的解析器可以用来为最终目标: 私人无效HtmlAgilityPack(字符串code){
VAR requestUri =的String.Format(“http://whois.sk-nic.sk/index.jsp?whois={0}”,code);
VAR要求=新HtmlWeb();
VAR的HTMLDocument = request.Load(requestUri);
变量名称= htmlDocument.DocumentNode.SelectSingleNode(\"/html/body/table[1]/tr[5]/td/table/tr[2]/td[2]\").InnerText.Trim();
VAR组织= htmlDocument.DocumentNode.SelectSingleNode(\"/html/body/table[1]/tr[5]/td/table/tr[3]/td[2]\").InnerText.Trim();}
本文地址: &
扫一扫关注官方微信&>&使用httpClient组件解析html并解决字符编码
使用httpClient组件解析html并解决字符编码
上传大小:25KB
使用httpclient 3.0解析html,实际使用当中遇到的字符集编码乱码问题,主要用于网页的信息采集,此外还列出一部分截取字符串的方法,带源码
httpclient3.0 自己下载jar包
综合评分:4(8位用户评分)
所需积分:
下载个数:50
{%username%}回复{%com_username%}{%time%}\
/*点击出现回复框*/
$(".respond_btn").on("click", function (e) {
$(this).parents(".rightLi").children(".respond_box").show();
e.stopPropagation();
$(".cancel_res").on("click", function (e) {
$(this).parents(".res_b").siblings(".res_area").val("");
$(this).parents(".respond_box").hide();
e.stopPropagation();
/*删除评论*/
$(".del_comment_c").on("click", function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_invalid/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parents(".conLi").remove();
alert(data.msg);
$(".res_btn").click(function (e) {
var q = $("#form1").serializeArray();
console.log(q);
var res_area_r = $.trim($(".res_area_r").val());
if (res_area_r == '') {
$(".res_text").css({color: "red"});
$.post("/index.php/comment/do_comment_reply/", q,
function (data) {
if (data.succ == 1) {
var $target,
evt = e || window.
$target = $(evt.target || evt.srcElement);
var $dd = $target.parents('dd');
var $wrapReply = $dd.find('.respond_box');
console.log($wrapReply);
var mess = $(".res_area_r").val();
var str = str.replace(/{%header%}/g, data.header)
.replace(/{%href%}/g, 'http://' + window.location.host + '/user/' + data.username)
.replace(/{%username%}/g, data.username)
.replace(/{%com_username%}/g, _username)
.replace(/{%time%}/g, data.time)
.replace(/{%id%}/g, data.id)
.replace(/{%mess%}/g, mess);
$dd.after(str);
$(".respond_box").hide();
$(".res_area_r").val("");
$(".res_area").val("");
$wrapReply.hide();
alert(data.msg);
}, "json");
/*删除回复*/
$(".rightLi").on("click",'.del_comment_r', function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_comment_del/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parent().parent().parent().parent().parent().remove();
$(e.target).parents('.res_list').remove()
alert(data.msg);
//填充回复
function KeyP(v) {
$(".res_area_r").val($.trim($(".res_area").val()));
评论共有2条
还行,看看也不错
东西蛮好的。。。。
审核通过送C币
Web前端学习电子书
创建者:zhouyou96
chm参考手册
创建者:sinat_
上传者其他资源上传者专辑
iscroll+flipsnap实现左右上下滑动
richfaces的jar包+demo
spring3+struts2+hibernate3+mysql驱动全部jar包
jsf+facelets+ajax4jsf的全部jar包
jsf增删改查带数据库
开发技术热门标签
VIP会员动态
前端开发重难点
17年软考最新真题及解析
物联网全栈开发专题
二十大技术领域优质资源
spring mvc+mybatis+mysql+maven+bootstrap 整合实现增删查改简单实例.zip
CSDN&VIP年卡&4000万程序员的必选
使用httpClient组件解析html并解决字符编码
会员到期时间:剩余下载个数:
积分不足!
资源所需积分
当前拥有积分
您可以选择
程序员的必选
绿色安全资源
资源所需积分
当前拥有积分
VIP年卡全年1200个资源免积分下载
你当前的下载分为234。
你还不是VIP会员
开通VIP会员权限,免积分下载
你下载资源过于频繁,请输入验证码
你下载资源过于频繁,请输入验证码
您因违反CSDN下载频道规则而被锁定帐户,如有疑问,请联络:!
若举报审核通过,可奖励20下载分
被举报人:
举报的资源分:
请选择类型
资源无法下载
资源无法使用
标题与实际内容不符
含有危害国家安全内容
含有反动色情等内容
含广告内容
版权问题,侵犯个人或公司的版权
*详细原因:HttpClient4 POST数据及问题 - 玮哥也是哥 - ITeye博客
博客分类:
post 方式挂参数的三种格式, mark一下。
其中尤其需要注意的是下面这个error()的调用方法,使用到MultipartEntity 带3个参数的完整 , 会导致请求参数在服务器端无法获取到post参数!
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, charsetObj);
but上面这个new MultipartEntity,如果使用无参的构造函数则一切ok, public MultipartEntity()
--------------
具体细节待深究
import java.io.IOE
import java.io.UnsupportedEncodingE
import java.nio.charset.C
import java.util.ArrayL
import java.util.L
import org.apache.http.HttpE
import org.apache.http.HttpR
import org.apache.http.NameValueP
import org.apache.http.ParseE
import org.apache.http.client.ClientProtocolE
import org.apache.http.client.HttpC
import org.apache.http.client.entity.UrlEncodedFormE
import org.apache.http.client.methods.HttpP
import org.apache.http.entity.StringE
import org.apache.http.entity.mime.HttpMultipartM
import org.apache.http.entity.mime.MultipartE
import org.apache.http.entity.mime.content.StringB
import org.apache.http.impl.client.DefaultHttpC
import org.apache.http.message.BasicNameValueP
import org.apache.http.util.EntityU
public class Test {
final static String URL = "http://localhost/";
final static Charset charsetObj = Charset.forName("utf-8");
public static void main(String[] args) throws Exception {
method3();
public static void demo() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
// 目标地址
HttpPost httppost = new HttpPost(URL);
// 构造最简单的字符串数据
StringEntity reqEntity = new StringEntity("firstname=abcde&lastname=fghi");
// 设置类型
reqEntity.setContentType("application/x-www-form-urlencoded");
// 设置请求的数据
httppost.setEntity(reqEntity);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity entity = httpresponse.getEntity();
String body = EntityUtils.toString(entity);
System.out.println(body);
public static void error() {
int tryTimes = 3;
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, charsetObj);
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
HttpPost httppost = new HttpPost(URL);
multipartEntity.addPart("firstname", new StringBody("xxxxxxxxxxxxxxxxxxxxxxx",charsetObj));
multipartEntity.addPart("lastname", new StringBody("yyyyyyyyyyyyyyyyyyyyyyy",charsetObj));
//设置连接超时时间
//设置读取response超时时间
httppost.setEntity(multipartEntity);
HttpResponse httpresponse = client.execute(httppost);
HttpEntity entity = httpresponse.getEntity();
String body = EntityUtils.toString(entity);
System.out.println(body);
}catch (Exception e) {
System.out.println(e);
public static void method3() {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List&NameValuePair& params = new ArrayList&NameValuePair&();
params.add(new BasicNameValuePair("email", ""));
params.add(new BasicNameValuePair("pwd", "xxx"));
params.add(new BasicNameValuePair("save_login", "1"));
// Post请求
// 设置参数
httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
// 发送请求
HttpResponse httpresponse = client.execute(httppost);
HttpEntity entity = httpresponse.getEntity();
String body = EntityUtils.toString(entity);
System.out.println(body);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
浏览 27944
浏览: 341330 次
来自: 深圳
当然,在tomcat还有JPDA这种方式 ,来远程debug: ...
好,语言简单明了易懂
&b&行不行&/b&
请教下,我这样:JSONObject jsonObject = ...1773人阅读
HttpClient(2)
下面的类已经说的很明白了
package com.example.
import java.io.BufferedR
import java.io.InputStreamR
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import org.apache.http.HttpE
import org.apache.http.HttpR
import org.apache.http.HttpS
import org.apache.http.NameValueP
import org.apache.http.client.HttpC
import org.apache.http.client.entity.UrlEncodedFormE
import org.apache.http.client.methods.HttpG
import org.apache.http.client.methods.HttpP
import org.apache.http.client.params.HttpClientP
import org.apache.http.impl.client.DefaultHttpC
import org.apache.http.message.BasicNameValueP
import org.apache.http.params.BasicHttpP
import org.apache.http.params.HttpConnectionP
import org.apache.http.params.HttpP
import org.json.JSONA
import org.json.JSONO
import android.app.A
import android.os.B
public class MainActivity extends Activity {
private final String uriString=&your url&;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//服务器返回的JSON数据
JSONObject jsonObject=this.getJSONObjectByGet();
//从JSON中得到字符串
String apiString=jsonObject.getString(&api&);
String countString=jsonObject.getString(&count&);
System.out.println(&apiString=&+apiString+&,countString=&+countString);
//从JSON中得到JSONArray,并且遍历
JSONArray jsonArray=jsonObject.getJSONArray(&data&);
for (int i = 0; i & jsonArray.length(); i++) {
JSONObject everyJsonObject=jsonArray.getJSONObject(i);
String category_id=everyJsonObject.getString(&category_id&);
String category_name=everyJsonObject.getString(&category_name&);
String category_rgb=everyJsonObject.getString(&category_rgb&);
String category_news_count=everyJsonObject.getString(&category_news_count&);
System.out.println(&category_id=&+category_id+&,category_name=&+category_name+
&,category_rgb=&+category_rgb+&,category_news_count=&+category_news_count);
System.out.println(&=====================================================&);
} catch (Exception e) {
e.printStackTrace();
//得到HttpClient
public HttpClient getHttpClient(){
HttpParams mHttpParams=new BasicHttpParams();
//设置网络链接超时
//即:Set the timeout in milliseconds until a connection is established.
HttpConnectionParams.setConnectionTimeout(mHttpParams, 20*1000);
//设置socket响应超时
//即:in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(mHttpParams, 20*1000);
//设置socket缓存大小
HttpConnectionParams.setSocketBufferSize(mHttpParams, 8*1024);
//设置是否可以重定向
HttpClientParams.setRedirecting(mHttpParams, true);
HttpClient httpClient=new DefaultHttpClient(mHttpParams);
return httpC
//得到JSONObject(Get方式)
public JSONObject getJSONObjectByGet(){
JSONObject resultJsonObject=
if (&&.equals(uriString)||uriString==null) {
HttpClient httpClient=this.getHttpClient();
StringBuilder urlStringBuilder=new StringBuilder(uriString);
StringBuilder entityStringBuilder=new StringBuilder();
//利用URL生成一个HttpGet请求
HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
BufferedReader bufferedReader=
HttpResponse httpResponse=
//HttpClient发出一个HttpGet请求
httpResponse=httpClient.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
//得到httpResponse的状态响应码
int statusCode=httpResponse.getStatusLine().getStatusCode();
if (statusCode==HttpStatus.SC_OK) {
//得到httpResponse的实体数据
HttpEntity httpEntity=httpResponse.getEntity();
if (httpEntity!=null) {
bufferedReader=new BufferedReader
(new InputStreamReader(httpEntity.getContent(), &UTF-8&), 8*1024);
String line=
while ((line=bufferedReader.readLine())!=null) {
entityStringBuilder.append(line+&/n&);
//利用从HttpEntity中得到的String生成JsonObject
resultJsonObject=new JSONObject(entityStringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
return resultJsonO
//----------------------------------------以下为POST请求
//准备进行POST请求的参数,一般而言将这些参数封装在HashMap中
public JSONObject save(String title, String timelength) throws Exception{
Map&String,String& paramsHashMap = new HashMap&String, String&();
paramsHashMap.put(&title&, title);
paramsHashMap.put(&timelength&, timelength);
paramsHashMap.put(&method&, &save&);
String path = &your url&;
return getJSONObjectByPost(path, paramsHashMap, &UTF-8&);
//得到JSONObject(Post方式)
//此方法此处未调用测试
public JSONObject getJSONObjectByPost(String path,Map&String, String& paramsHashMap, String encoding) {
JSONObject resultJsonObject =
List&NameValuePair& nameValuePairArrayList = new ArrayList&NameValuePair&();
// 将传过来的参数填充到List&NameValuePair&中
if (paramsHashMap != null && !paramsHashMap.isEmpty()) {
for (Map.Entry&String, String& entry : paramsHashMap.entrySet()) {
nameValuePairArrayList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
UrlEncodedFormEntity entity =
// 利用List&NameValuePair&生成Post请求的实体数据
// 此处使用了UrlEncodedFormEntity!!!
entity = new UrlEncodedFormEntity(nameValuePairArrayList, encoding);
HttpPost httpPost = new HttpPost(path);
// 为HttpPost设置实体数据
httpPost.setEntity(entity);
HttpClient httpClient = this.getHttpClient();
// HttpClient发出Post请求
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 得到httpResponse的实体数据
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpEntity.getContent(),&UTF-8&), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line =
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line + &/n&);
// 利用从HttpEntity中得到的String生成JsonObject
resultJsonObject = new JSONObject(entityStringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
return resultJsonO
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:304754次
积分:4521
积分:4521
排名:第6744名
原创:133篇
转载:214篇
评论:27条
(7)(12)(3)(7)(5)(10)(8)(4)(5)(10)(7)(6)(9)(8)(18)(1)(10)(12)(10)(8)(11)(6)(7)(9)(2)(4)(9)(4)(11)(21)(26)(1)(7)(9)(6)(16)(31)(7)
(window.slotbydup = window.slotbydup || []).push({
id: '4740881',
container: s,
size: '200,200',
display: 'inlay-fix'

我要回帖

更多关于 httpclient maven 的文章

 

随机推荐