java发送socket请求和用socket发送http请求求的区别

java发送HttpClient请求及接收请求结果过程的简单实例
投稿:jingxian
字体:[ ] 类型:转载 时间:
下面小编就为大家带来一篇java发送HttpClient请求及接收请求结果过程的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
1、写一个HttpRequestUtils工具类,包括post请求和get请求
package com.brainlong.framework.util.
import net.sf.json.JSONO
import mons.httpclient.HttpS
import org.apache.http.HttpR
import org.apache.http.client.methods.HttpG
import org.apache.http.client.methods.HttpP
import org.apache.http.entity.StringE
import org.apache.http.impl.client.DefaultHttpCimport org.apache.http.util.EntityU
import org.slf4j.L
import org.slf4j.LoggerF
import java.io.IOEimport java.net.URLD public class HttpRequestUtils {
private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);
//日志记录
* httpPost
* @param url 路径
* @param jsonParam 参数
public static JSONObject httpPost(String url,JSONObject jsonParam){
return httpPost(url, jsonParam, false);
* post请求
* @param url
* @param jsonParam
* @param noNeedResponse
不需要返回结果
public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject jsonResult =
HttpPost method = new HttpPost(url);
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
String str = "";
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity());
if (noNeedResponse) {
/**把json字符串转换成json对象**/
jsonResult = JSONObject.fromObject(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
return jsonR
* 发送get请求
* @param url
public static JSONObject httpGet(String url){
//get请求返回结果
JSONObject jsonResult =
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
/**把json字符串转换成json对象**/
jsonResult = JSONObject.fromObject(strResult);
url = URLDecoder.decode(url, "UTF-8");
logger.error("get请求提交失败:" + url);
} catch (IOException e) {
logger.error("get请求提交失败:" + url, e);
return jsonR
2、写业务代码发送Http请求
3、MVC配置文件设置Controller扫描目录
&!-- 自动扫描且只扫描@Controller --&
&context:component-scan base-package="com.wiselong.multichannel" use-default-filters="false"&
&context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /&
&/context:component-scan&
4、接收Http请求
接收post请求
@Controller
@RequestMapping(value&=&"/api/platform/exceptioncenter/exceptioninfo")
public&class&ExceptionInfoController&{
@Autowired
private&ExceptionInfoBiz&exceptionInfoB
*&创建异常信息请求
*&@param&requestBody&请求消息内容
*&@param&request&请求消息头
*&@return&jsonObject
@RequestMapping(
value="/create",
method&=&RequestMethod.POST
public&ModelAndView&createExceptionInfo(@RequestBody&String&requestBody,&HttpServletRequest&request)&{
JSONObject&jsonObject&=&JSONObject.fromObject(requestBody);
ComExceptionInfo&comExceptionInfo&=&new&ComExceptionInfo();
comExceptionInfo.setProjectName(jsonObject.getString("projectName"));
comExceptionInfo.setTagName(jsonObject.getString("tagName"));
exceptionInfoBiz.insert(comExceptionInfo);
//返回请求结果
JSONObject&result=&new&JSONObject();
result.put("success",&"true");
return&new&ModelAndView("",&ResponseUtilsHelper.jsonSuccess(result.toString()));
接收get请求
@Controller
@RequestMapping(value="/api/platform/messagecenter/messages/sms")
public&class&SmsController&{
@Autowired
SmsSendBiz&smsSendB
*&接收手机号码和内容往短信发送表插入一条记录
*&@param&requestbody&请求消息内容
*&@param&request&请求消息头
*&@return&jsonObject
@RequestMapping(
value="/send",
method=&RequestMethod.GET
public&ModelAndView&sendSms(@RequestBody&String&requestbody,&HttpServletRequest&request)&{
//获取请求URL及url后面传输的参数
String&url&=&request.getRequestURL()&+&"?"&+&request.getQueryString();
url&=&BuildRequestUrl.decodeUrl(url);
String&telePhone&=&RequestUtils.getStringValue(request,&"telePhone");
String&content&=&RequestUtils.getStringValue(request,&"content");
smsSendBiz.insertTtMsQuequ(telePhone,content);
return&new&ModelAndView("",&ResponseUtilsHelper.jsonResult("",&true));
import&java.io.BufferedR
import&java.io.IOE
import&java.io.InputS
import&java.io.InputStreamR
import&mons.httpclient.HttpC
import&mons.httpclient.HttpM
import&mons.httpclient.methods.GetM
public&class&H_client_get&{
public&static&void&main(String[]&args)&throws&IOException&{
//&new类对象
HttpClient&client&=&new&HttpClient();
//&使用&GET&方法&与URL服务器进行交互
//&HttpMethod&method&=&new&GetMethod("http://192.168.111.128/bak/regist.php?email=&password=1234567&re_password=1234567&username=admin&nickname=管理员");
HttpMethod&method&=&new&GetMethod("http://192.168.111.128/bak/login.php?username=");
//&使用&GET&方法&,实行与url服务器连接
client.executeMethod(method);
//&数据流输出
//&method.getResponseBodyAsStream&创建字节流对象为inputStream
InputStream&inputStream&=&method.getResponseBodyAsStream();
//&InputStreamReader(inputStream)字节流转换成字符流&BufferedReader封装成带有缓冲的字符流对象了&
BufferedReader&br&=&new&BufferedReader(new&InputStreamReader(inputStream,"UTF-8"));
//&StringBuffer是字符串变量,它的对象是可以扩充和修改的&创建一个空的StringBuffer类的对象&
StringBuffer&stringBuffer&=&new&StringBuffer();
//&定义字符串常量
String&str=&"";
//&br字符流赋值给str字符串常量&str不等于空&按行输出
while((str&=&br.readLine())&!=&null){&
//&StringBuffer&是字符串变量,它的对象是可以扩充和修改的&将str数据赋予&stringBuffer&
stringBuffer&.append(str&);&
//&按照字符串循环输出stringBuffer
System.out.println(stringBuffer.toString());
//&关闭method&的&httpclient连接
method.releaseConnection();
import&java.io.BufferedR
import&java.io.IOE
import&java.io.InputS
import&java.io.InputStreamR
import&mons.httpclient.methods.PostM
import&mons.httpclient.*;
public&class&H_client_post&{
public&static&void&main(String[]&args)&throws&IOException&{
HttpClient&client&=&new&HttpClient();
PostMethod&method&=&new&PostMethod("http://192.168.111.128/bak/login_post.php");
//表单域的值,既post传入的key=value
NameValuePair[]&date&=&{&new&NameValuePair("username","admin"),new&NameValuePair("password","123457")};
//method使用表单阈值
method.setRequestBody(date);
//提交表单
client.executeMethod(method);
//字符流转字节流&循环输出,同get解释
InputStream&inputStream&=&method.getResponseBodyAsStream();
BufferedReader&br&=&new&BufferedReader(new&InputStreamReader(inputStream,"UTF-8"));
StringBuffer&stringBuffer&=&new&StringBuffer();
String&str=&"";
while((str&=&br.readLine())&!=&null){&
stringBuffer&.append(str&);&
System.out.println(stringBuffer.toString());
method.releaseConnection();
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1
2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
3. 支持HTTPS协议。
4. 通过Http代理建立透明的连接。
5. 利用CONNECT方法通过Http代理建立隧道的https连接。
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。
7. 插件式的自定义认证方案。
8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
10. 自动处理Set-Cookie中的Cookie。
11. 插件式的自定义Cookie策略。
12. Request的输出流可以避免流中内容直接缓冲到socket服务器。
13. Response的输入流可以有效的从socket服务器直接读取相应内容。
14. 在http1.0和http1.1中利用KeepAlive保持持久连接。
15. 直接获取服务器发送的response code和 headers。
16. 设置连接超时的能力。
17. 实验性的支持http1.1 response caching。
18. 源代码基于Apache License 可免费获取。
三、使用方法
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
package com.
import java.io.F
import java.io.FileInputS
import java.io.IOE
import java.io.UnsupportedEncodingE
import java.security.KeyManagementE
import java.security.KeyS
import java.security.KeyStoreE
import java.security.NoSuchAlgorithmE
import java.security.cert.CertificateE
import java.util.ArrayL
import java.util.L
import javax.net.ssl.SSLC
import org.apache.http.HttpE
import org.apache.http.NameValueP
import org.apache.http.ParseE
import org.apache.http.client.ClientProtocolE
import org.apache.http.client.entity.UrlEncodedFormE
import org.apache.http.client.methods.CloseableHttpR
import org.apache.http.client.methods.HttpG
import org.apache.http.client.methods.HttpP
import org.apache.http.conn.ssl.SSLConnectionSocketF
import org.apache.http.conn.ssl.SSLC
import org.apache.http.conn.ssl.TrustSelfSignedS
import org.apache.http.entity.ContentT
import org.apache.http.entity.mime.MultipartEntityB
import org.apache.http.entity.mime.content.FileB
import org.apache.http.entity.mime.content.StringB
import org.apache.http.impl.client.CloseableHttpC
import org.apache.http.impl.client.HttpC
import org.apache.http.message.BasicNameValueP
import org.apache.http.util.EntityU
import org.junit.T
public class HttpClientTest {
public void jUnitTest() {
* HttpClient连接SSL
public void ssl() {
CloseableHttpClient httpclient =
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
// 加载keyStore d:\\tomcat.keystore
trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
instream.close();
} catch (Exception ignore) {
// 相信自己的CA和所有自签名的证书
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// 只允许使用TLSv1协议
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// 创建http请求(get方式)
HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
} finally {
response.close();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} finally {
if (httpclient != null) {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
* post方式提交表单(模拟用户登录请求)
public void postForm() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 创建参数队列
List&namevaluepair& formparams = new ArrayList&namevaluepair&();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefE
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
} finally {
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
public void post() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 创建参数队列
List&namevaluepair& formparams = new ArrayList&namevaluepair&();
formparams.add(new BasicNameValuePair("type", "house"));
UrlEncodedFormEntity uefE
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
} finally {
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
* 发送 get请求
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httpget.
HttpGet httpget = new HttpGet("/");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
System.out.println("------------------------------------");
} finally {
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
* 上传文件
public void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
EntityUtils.consume(resEntity);
} finally {
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}&/namevaluepair&&/namevaluepair&&/namevaluepair&&/namevaluepair&
以上这篇java发送HttpClient请求及接收请求结果过程的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具理解:模拟登陆指定网站,登陆成功后,获取返回串中的cookie值用于发起下次请求。
package demo.http.
import java.io.IOE
import java.io.InputS
import java.io.UnsupportedEncodingE
import java.net.S
import java.net.UnknownHostE
import java.util.ArrayL
public class JavaHttpClient {
// common parameters
private static String serverIP = &192.168.30.205&;
private static int serverPort = 80;
private static String charset = &GBK&;
// login parameters
private static String loginUrl = &/picp/SecurityAction.do?method=login&;
private static String loginNameIndex = &piUsersDto.usercode&;// 用户名索引
private static String loginPwdIndex = &piUsersDto.password&;// 密码索引
private static String loginName = &100001&;//登陆用户名
private static String loginPwd = &111111&;//登陆密码
private static String cookieIndex = &Set-Cookie: JSESSIONID=&;//cookie索引串
// check operation parameters
private static String checkUrl=&/picp/SingleInquireAction.do?method=query&;
private static String checkNameIndex=&certname&;//查询名字索引
private static String checkIdNumIndex=&certno&;//查询证件号码索引
private static String checkType=&businesscode&;//查询类型
public static void main(String[] args) {
JavaHttpClient obj=new JavaHttpClient();
Socket clientSocket=
clientSocket=new Socket(serverIP, serverPort);
clientSocket.setSoTimeout(20*1000);
String cookieValue=obj.login(clientSocket);
if(cookieValue!=null){//check
obj.checkOpt(clientSocket, cookieValue);
}catch (Exception e) {
e.printStackTrace();
if(clientSocket!=null){
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
/* 登陆操作,成功后返回cookie */
private String login(Socket clientSocket) {
String cookieValue=
String loginStr=createLoginReqStr();
clientSocket.getOutputStream().write(loginStr.getBytes(charset));
clientSocket.getOutputStream().flush();
String loginResponseStr=getResponseStr(clientSocket.getInputStream());
//判断是否登陆成功
cookieValue=getCookieStr(loginResponseStr);
}catch (Exception e) {
e.printStackTrace();
return cookieV
/*组织登陆串*/
private String createLoginReqStr() {
String loginStr = loginNameIndex + &=& + loginName + &&&
+ loginPwdIndex + &=& + loginP
StringBuffer sBuf = new StringBuffer();
sBuf.append(&POST & + loginUrl + & & + &HTTP/1.1\r\n&);
sBuf.append(&Accept: &+ &text/html, application/xhtml+xml, */*\r\n&);
sBuf.append(&Accept-Language: zh_CN\r\n&);
sBuf.append(&Content-Type: application/x-www-form-urlencoded\r\n&);
sBuf.append(&Host: & + serverIP + &:& + serverPort + &\r\n&);
sBuf.append(&Content-Length: & + loginStr.getBytes(charset).length+&\r\n&);
sBuf.append(&Connection: Keep-Alive\r\n&);
sBuf.append(&Cache-Control: no-cache\r\n&);
sBuf.append(&\r\n&);
sBuf.append(loginStr);
return sBuf.toString();
} catch (Exception e) {
e.printStackTrace();
/*查询操作*/
private void checkOpt(Socket clientSocket,String cookieValue){
String checkStr=createCheckReqStr(cookieValue);
clientSocket.getOutputStream().write(checkStr.getBytes(charset));
clientSocket.getOutputStream().flush();
String checkResponseStr=getResponseStr(clientSocket.getInputStream());
} catch (Exception e) {
e.printStackTrace();
/*组织查询串*/
private String createCheckReqStr(String cookieValue) {
StringBuffer sBuf=new StringBuffer();
String checkStr=checkType+&=&+&01&&+checkNameIndex+&=&+&熊大&+&&&+checkIdNumIndex+&=&+&047763&;
for(int i=1;i&5;i++){
checkStr=checkStr+&&&+checkNameIndex+&=&&+checkIdNumIndex+&=&;
sBuf.append(&POST & + checkUrl + & & + &HTTP/1.1\r\n&);
sBuf.append(&Accept: &+ &text/html, application/xhtml+xml, */*\r\n&);
sBuf.append(&Accept-Language: zh_CN\r\n&);
sBuf.append(&Content-Type: application/x-www-form-urlencoded\r\n&);
sBuf.append(&Host: & + serverIP + &:& + serverPort + &\r\n&);
sBuf.append(&Content-Length: & + checkStr.getBytes(charset).length+&\r\n&);
sBuf.append(&Connection: Keep-Alive\r\n&);
sBuf.append(&Cache-Control: no-cache\r\n&);
sBuf.append(&Cookie: JSESSIONID=&+cookieValue+&\r\n&);
sBuf.append(&\r\n&);
sBuf.append(checkStr);
} catch (Exception e) {
e.printStackTrace();
return sBuf.toString();
/*获取返回值*/
private String getResponseStr(InputStream ins){
StringBuffer sBuf=new StringBuffer();
int contentLength=0;//存储http header中contentLength的值
String aLine=
aLine=readFromStream(ins, 0);
if(aLine.contains(&Content-Length&)){
contentLength=Integer.parseInt(aLine.split(&:&)[1].trim());
sBuf.append(aLine);
}while(!aLine.equals(&\r\n&));
sBuf.append(readFromStream(ins, contentLength));
} catch (Exception e) {
e.printStackTrace();
return sBuf.toString();
/* 从流中读取指定长度的字节,readLenth为0时,读取一行 */
private String readFromStream(InputStream ins, int readLength) {
byte tmpB;
byte[] byteA
if (readLength == 0) {// 读取一行
ArrayList byteList = new ArrayList();
tmpB = (byte) ins.read();
byteList.add(tmpB);
} while (tmpB != 10);// 判断是否换行
byteArr = new byte[byteList.size()];
for (int i = 0; i & byteList.size(); i++) {
byteArr[i] = (Byte) byteList.get(i);
byteList.clear();
} else {// 读取指定长度
int index = 0;
byteArr = new byte[readLength];
byteArr[index] = (byte) ins.read();
} while (index & readLength);
return new String(byteArr, charset);
} catch (Exception e) {
e.printStackTrace();
/*获取cookie值*/
private String getCookieStr(String loginResponseStr){
String cookieValue=
int index=loginResponseStr.indexOf(cookieIndex);
System.out.println(index);
if(index&-1){
cookieValue = loginResponseStr.substring(index + 23, index + 55);
} catch (Exception e) {
e.printStackTrace();
return cookieV
本文已收录于以下专栏:
相关文章推荐
在上次Java Socket现实简单的HTTP服务我们实现了简单的HTTP服务,它可以用来模拟HTTP服务,用它可以截获HTTP请求的原始码流,让我们很清楚的了解到我们向服务发的HTTP消息的结构,对...
在上次Java Socket现实简单的HTTP服务我们实现了简单的HTTP服务,它可以用来模拟HTTP服务,用它可以截获HTTP请求的原始码流,让我们很清楚的了解到我们向服务发的HTTP消息的结构,对...
http://blog.csdn.net/a9529lty/article/details/7174265
在上次Java Socket现实简单的HTTP服务我们实现了简单的HTTP...
在上次Java Socket现实简单的HTTP服务我们实现了简单的HTTP服务,它可以用来模拟HTTP服务,用它可以截获HTTP请求的原始码流,让我们很清楚的了解到我们向服务发的HTTP消息的结构,对...
采用JAVA的socket模拟HTTP请求发送文件,希望对大家有帮助!!!
@auther zhaojie
网络传输过程:
1,找到对方ip
2,数据发送到指定端口(每个应用程序对应一个端口)
3,定义通信规则,即协议   TCP/IP
1,面向无连接,将数据、源、目的封装(像邮递东西)
2,数据...
使用Java socket模拟HTTP服务器
&?php/** Network: HTTP request object* Author: Li HouYu (Karajan Lee), Shanghai, China.*/class HttpR...
* Network: HTTP request object* Author: Li HouYu (Karajan Lee), Shanghai, China.
他的最新文章
讲师:王哲涵
讲师:韦玮
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)

我要回帖

更多关于 socket发送http请求 的文章

 

随机推荐