1.使用HttpURLConnection

    public static String getJsonByURL(String base_url) {
String url = base_url;
StringBuilder json = new StringBuilder();
String result = ""; try {
URL u = new URL(url);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setRequestMethod("GET");
//uc.setRequestMethod("POST");
/*
String cookieVal =uc.getHeaderField("Set-Cookie"); //获取session
String JSESSIONID = (cookieVal.substring(0,cookieVal.indexOf(";")));
uc.setRequestProperty("Cookie", JSESSIONID);//设置session
*/
BufferedReader bd = new BufferedReader(new InputStreamReader(uc.getInputStream(),"GBK"));
String s = null;
while((s=bd.readLine())!=null) {
json.append(s);
}
bd.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = json.toString(); return result;
}

2.使用HttpClient

(1)get

    public static String getJsonByGet(String url) {
String s = "";
//CloseableHttpClient httpclient = HttpClients.createDefault();
DefaultHttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
response = httpclient.execute(httpget);
entity = response.getEntity();
/*
CookieStore cookieStore = httpclient.getCookieStore();//获取cookies
httpclient.setCookieStore(cookieStore);//设置cookies
*/
s = EntityUtils.toString(entity, "UTF-8");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
httpclient.close();
}
return s;
}

(POST)

   public static String getJsonByPost(String url) {  

        DefaultHttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
//CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url); CloseableHttpResponse response = null;
HttpEntity entity = null;
String s = "";
try {
response = httpclient.execute(httppost);
entity = response.getEntity();
s = EntityUtils.toString(entity, "UTF-8");
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace(); }finally {
httpclient.close();
}
return s;
}

获取cookies和设置cookies的位置要根据不同的接口而定。

以上的方法是把接口的参数,在调用方法之前就配好了,作为url传入。也可在调用的相应方法内部做处理。

1.使用HttpURLConnection

    public static byte[] getJsonByURL(String url, String params) throws Exception{
URL url = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");//
// conn.setConnectTimeout(10000);//
// conn.setReadTimeout(2000);//
conn.setDoOutput(true);//
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream=conn.getInputStream();
return StreamTool.readInputStream(inStream);
}

对参数的处理有很多方法,可以append(),也可以自己+,不同参数,不同方法重载

2.使用HttpClient

package com.tradeyun;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
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.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* @author QiaoJiafei
* @version 创建时间:2015年12月18日 上午10:03:12
* 类说明
*/
public class TestHttpClientParameter {
public static void main(String args[]) {
/* HttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
String s = "";
HttpResponse response = null;
HttpEntity entity = null;
String url = "http://172.16.30.244:8090/gm_product_site/assignmentApply/auth";
System.out.println("url=========="+url);
HttpPost post = new HttpPost(url);
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("applyId","1"));
formparams.add(new BasicNameValuePair("isPass","true"));
//formparams.add(new BasicNameValuePair("pwd","aaaaaa1"));
//formparams.add(new BasicNameValuePair("pwd", "aaaaaa1"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); post.setEntity(uefEntity);
System.out.println("executing request " + post.getURI());
response = httpclient.execute(post);
entity = response.getEntity();
s= EntityUtils.toString(entity, "UTF-8");
System.out.println(s); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */ //不成功
TestHttpClientParameter t = new TestHttpClientParameter();
t.post3();
} public void post3() {
HttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
String s = "";
HttpResponse response = null;
HttpEntity entity = null;
String url = "http://172.16.30.244:8090/gm_product_site/assignmentApply/auth";
System.out.println("url=========="+url);
HttpPost post = null;
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("applyId","1"));
formparams.add(new BasicNameValuePair("isPass","true")); UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); URI uri=null;
try {
uri = URIUtils.createURI("http", "172.16.30.244:8090", -1, "/gm_product_site/assignmentApply/auth",
URLEncodedUtils.format(formparams, "UTF-8"), null);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
post = new HttpPost(uri);
System.out.println(post.getURI());
response = httpclient.execute(post);
entity = response.getEntity();
s= EntityUtils.toString(entity, "UTF-8");
System.out.println(s); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

httpclient也可以使用下面的方式:

package com.core.execute;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; 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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* @author QiaoJiafei
* @version 创建时间:2016年3月2日 上午10:54:24
* 类说明
*/
public class TestMapPara {
static HttpClient client = HttpClients.createDefault(); public static void main(String args[]) {
Map<String, String> map = new HashMap<String, String>();
map.put("id", "22");
postmap(map);
} private static void postmap(Map<String, String> params) {
// TODO Auto-generated method stub
String url = "http://172.16.30.73:8080/test/user/update";
HttpPost httppost = new HttpPost(url);
List<NameValuePair> ps = new ArrayList<NameValuePair>();
for (String pKey : params.keySet()) {
ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
}
try {
httppost.setEntity(new UrlEncodedFormEntity(ps));
       //上面一行代码也可以使用带有编码格式的构造方法,如new UrlEncodedFormEntity(ps, "UTF-8");
HttpResponse response = client.execute(httppost);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }

java使用HttpURLConnection和HttpClient分别模拟get和post请求以及操作cookies的更多相关文章

  1. java 的http请求方式:HttpURLConnection和HttpClient

    1.要了解一些概念性的东西,比如Http的协议以及协议头等一些东东 2.HttpURLConnection一般步骤:创建URL对象==>获取URL的HttpURLConnection对象实例== ...

  2. HttpClient方式模拟http请求

    方式一:HttpClient import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.http.*; im ...

  3. Java使用HttpURLConnection上传文件

    从普通Web页面上传文件非常easy.仅仅须要在form标签叫上enctype="multipart/form-data"就可以,剩余工作便都交给浏览器去完毕数据收集并发送Http ...

  4. Java使用HttpURLConnection上传文件(转)

    从普通Web页面上传文件很简单,只需要在form标签叫上enctype="multipart/form-data"即可,剩余工作便都交给浏览器去完成数据收集并发送Http请求.但是 ...

  5. Android HttpURLConnection And HttpClient

    Google的工程师的一个博客写到: HttpURLConnection和HttpClient Volley HTTP请求时:在Android 2.3及以上版本,使用的是HttpURLConnecti ...

  6. android中的HttpURLConnection和HttpClient实现app与pc数据交互

    自学android的这几天很辛苦,但是很满足,因为每当学到一点点知识点都会觉得很开心,觉得今天是特别有意义的,可能这个就是一种莫名的热爱吧. 下面来说说今天学习的HttpURLConnection和H ...

  7. android 网络编程之HttpURLConnection与HttpClient使用与封装

    1.写在前面     大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议.     本文并 ...

  8. Android网络连接之HttpURLConnection和HttpClient

    1.概念   HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.在 JDK 的 java.net 包中 ...

  9. HttpURLConnection和HttpClient

    HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.在 JDK 的 java.net 包中已经提供了访问 ...

随机推荐

  1. Verilog学习笔记简单功能实现(三)...............同步有限状态机

    在Verilog中可以采用多种方法来描述有限状态机最常见的方法就是用always和case语句.如下图所示的状态转移图就表示了一个简单的有限状态机: 图中:图表示了一个四状态的状态机,输入为A和Res ...

  2. 微信公共平台开发4 .net

    之前说了让微信发送给关注我们的粉丝普通的文本信息,下面我们来看看如何发送图文信息,需要注意的是这里说的是,让微信发给我们,而不是我们拍个图片发给微信处理,上传图片在以后的再讲.下面是发送图文消息的函数 ...

  3. android布局--Android fill_parent、wrap_content和match_parent的区别

    来自:http://www.cnblogs.com/nikyxxx/archive/2012/06/15/2551390.html 三个属性都用来适应视图的水平或垂直大小,一个以视图的内容或尺寸为基础 ...

  4. android studio问题rendering problems no render target selected

    activity_main.xml选择Design显示rendering problems no render target selected 在stackOverflow上找到了答案: You ne ...

  5. AVL树详解

    AVL树 参考了:http://www.cppblog.com/cxiaojia/archive/2012/08/20/187776.html 修改了其中的错误,代码实现并亲自验证过. 平衡二叉树(B ...

  6. iOS设计模式之工厂方法模式

    工厂方法模式 基本理解 工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类.工厂方法使一个类的实例化延迟到其子类. 简单工厂的最大优点就是工厂类中包含了必要的逻辑判断,根据客户端的选择 ...

  7. JAVA基础学习day21--IO流三-File、Properties、PrintWriter与合并、分割流

    一.File 1.1.File概述 文件和目录路径名的抽象表示形式. 用户界面和操作系统使用与系统相关的路径名字符串 来命名文件和目录.此类呈现分层路径名的一个抽象的.与系统无关的视图.抽象路径名 有 ...

  8. CSS 指定选择器(十一)

    一.指定选择器 有时个会希望控制某个元素在一定范围内的对象样式,这时就可以把元素与Class或者Id选择器结合起来使用 <!DOCTYPE html PUBLIC "-//W3C//D ...

  9. OC中NSArray

    #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { ...

  10. FFT教你做乘法(FFT傅里叶变换)

    题目来源:https://biancheng.love/contest/41/problem/C/index FFT教你做乘法 题目描述 给定两个8进制正整数A和B(A和B均小于10000位),请利用 ...