`

java url与httpclient

    博客分类:
  • java
 
阅读更多

使用java客户端访问网站是程序猿必备的技能,java默认的包java.net就有支持

 

package Http.client;

import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;

/**
 * 类说明 使用官网的net类进行测试
 * 
 * @author rfk
 */
public class JavaNet {
	@SuppressWarnings("resource")
	public static void main(String args[]) {
		String urla = "https://www.baidu.com/";
		URL myUrl = null;
		try {
			myUrl = new URL(urla);
			InputStream input = myUrl.openStream();
			Scanner scan = new Scanner(input);
			scan.useDelimiter("\n");
			while (scan.hasNext()) {
				String str = scan.next();
				System.out.println(str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

此处使用的是get请求,地址拼接的方式,如果使用post请求,则需要设置表头。

 

package Http.client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 类说明
 * 
 * @author rfk
 */
public class TestHttpUrl {
	public static void main(String[] args) {
		URL url = null;
		try {
			url = new URL("http://localhost:9180/" + "abcde");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json");
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			String str = "传输的数据";
			out.writeBytes(str);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuffer buffer = new StringBuffer("");
			String lines;
			while ((lines = reader.readLine()) != null) {
				buffer.append(lines);
				reader.close();
				connection.disconnect();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

观察代码发现很麻烦,所以引用httpclient

 

package Http.client;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 类说明
 * 
 * @author rfk
 */
public class TestHttpClientGet {
	public static void main(String[] args) {
		// 如果此处String url="www.baidu.com"; 会出现错误
		String url = "http://www.baidu.cn/";
		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = null;
		try {
			response = client.execute(httpGet);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				String str = EntityUtils.toString(response.getEntity());
				System.err.println(str);
				File fi = new File("/Users/sona/Desktop/a.txt");
				if (fi.getParent() != null) {
					if (!fi.exists())
						fi.createNewFile();
					BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fi));
					out.write(str.getBytes());
					out.flush();
					out.close();
				} else {
					try {
						throw new Exception();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

 

如果是post请求,则代码如下

package Http.client;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

/**
 * 类说明
 * 
 * @author rfk
 */
public class TestHttpClientPost {
	public final static String url = "http://www.baidu.com";
	// 需要访问的地址
	public static void main(String[] args) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 创建一个HTTP访问的客户端
		HttpPost httpPost = new HttpPost(url);
		// 现在即将发送一个post请求 NameValuePair是一个接口
		List<NameValuePair> allParams = new ArrayList<NameValuePair>();
		// 需要将所有的请求参数进行一个封装的处理操作
		// public class BasicNameValuePair implements NameValuePair
		allParams.add(new BasicNameValuePair("msg", "世界,你好!"));
		// 追加传递参数
		allParams.add(new BasicNameValuePair("mid", "helloworld"));
		// 追加传递参数
		// 由于现在传递了中文,所以需要针对于中文进行编码的控制
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(allParams, "UTF-8");// 设置拜尼妈
		httpPost.setEntity(entity);
		// 将需要发送的数据与POST请求对象绑定在一起
		CloseableHttpResponse response = httpClient.execute(httpPost); // 发送GET请求
		System.out.println(response.getEntity());
		int status = response.getStatusLine().getStatusCode();
		if (status >= 200 && status < 300) {
			InputStream input = response.getEntity().getContent();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] data = new byte[1024];
			int len = 0;
			while ((len = input.read(data)) != -1) {
				bos.write(data, 0, len);
			}
			System.out.println(new String(bos.toByteArray()));
		} else {
			throw new ClientProtocolException("Unexpected response status: " + status);
		}
	}
}

如果需要在java客户段上传文件

 

package Http.client;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;

public class HttpClientUploadDemo {
	public static void main(String[] args) throws Exception {
		//需要上传的文件
		File file = new File("D:" + File.separator + "dog.jpg");
		//路径
		String url = "http://www.baidu.com";
		// 创建一个HttpClient操作类
		HttpClient httpClient = HttpClients.createDefault();
		//创建post
		HttpPost httpPost = new HttpPost(url);
		// 如果要上传文件则一定要使用“multipart/form-data”进行设置
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.addPart("photo", new FileBody(file, ContentType.create("image/jpeg")));
		builder.addPart("msg", new StringBody("世界,你好", ContentType.create("text/plain", Consts.UTF_8)));
		HttpEntity entity = builder.build(); // 定义上传实体类
		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost); // 发送post请求
		System.out.println(response.getEntity());
		System.out.println(response.getStatusLine().getStatusCode());
		InputStream input = response.getEntity().getContent();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		while ((len = input.read(data)) != -1) {
			bos.write(data, 0, len);
		}
		System.out.println(new String(bos.toByteArray()));
	}
}

 

下面的代码工具类转载自http://blog.csdn.net/u012878380/article/details/54907246

 

package Http.client;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
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.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 类说明
 * 
 * @author rfk
 */
public class HttpClientUtil {

	public static String doGet(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doPost(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
	
	public static String doPost(String url) {
		return doPost(url, null);
	}

	public static String doPostJson(String url, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
}

 

 代码上传到github:https://github.com/sona0402/url-httpclient.git

分享到:
评论

相关推荐

    java使用HttpClient通过url下载文件到本地

    综上所述,通过Java的HttpClient库,可以在Eclipse环境中编写程序,实现从指定URL下载文件到本地的功能。通过理解HttpClient的工作原理和提供的API,开发者可以构建出稳定、高效的文件下载解决方案。

    java httpclient 模拟登录

    在"java httpclient 模拟登录"这个场景下,我们通常会用到HttpClient来模拟用户登录网站的过程,获取登录后的session信息,以便后续能够访问登录后才能看到的页面内容。以下将详细介绍如何使用Java HttpClient进行...

    Java 使用HttpClient保持SESSION状态

    下面我们将详细探讨如何在Java中使用HttpClient来实现这一目标。 首先,我们需要导入必要的Apache HttpClient库,通常包含以下依赖: ```xml &lt;groupId&gt;org.apache.httpcomponents &lt;artifactId&gt;httpclient ...

    JAVA利用HttpClient进行HTTPS接口调用

    接下来,`HttpClientUtil.java`文件可能是实现HttpClient工具类,提供一个静态方法来创建和初始化HttpClient实例。这个方法可能包含以下步骤: 1. 创建一个CloseableHttpClient实例,通常使用HttpClientBuilder构建...

    JAVA httpclient jar下载

    httpclient常用封装工具 doGet(String url, Map, String&gt; param) doPost(String url, Map, String&gt; param) doPostJson(String url, String json)

    Java HttpClient 全部的jar包

    在Java项目中,使用HttpClient可以实现与Web服务器的高效通信。下面将详细介绍这12个jar包的作用及其在HttpClient中的功能: 1. `commons-beanutils-1.8.0.jar`: Apache Commons BeanUtils库提供了对Java Beans属性...

    JAVA调用HTTP及httpclient的详细说明

    而在Java编程语言中,开发者可以选择多种方式来实现HTTP请求的发送与接收,其中`HttpURLConnection`和`HttpClient`是两种常用的工具。本文将详细介绍如何使用`HttpURLConnection`以及`HttpClient`库来进行HTTP请求的...

    JAVA-用HttpClient来模拟浏览器GET,POST.docx

    JAVA使用HttpClient模拟浏览器GET、POST请求 在本文中,我们将介绍如何使用Apache Commons HttpClient库来模拟浏览器的GET和POST请求。HttpClient库是一个开放源码的项目,是Apache Commons项目的一部分,旨在简化...

    java 中HttpClient传输xml字符串实例详解

    Java中的HttpClient是一个强大的HTTP客户端库,常用于与服务器进行数据交互。在本实例中,我们将讲解如何使用HttpClient来传输XML字符串。首先,我们需要确保引入了正确的依赖,包括Apache HttpClient、HttpMime、...

    Java中Httpclient需要的jar包(httpclient.jar,httpcore.jar及commons-logging.jar)

    在这个例子中,我们首先创建了一个默认的HttpClient实例,然后定义了一个HttpGet请求对象,并指定目标URL。接着,我们通过HttpClient的execute方法发送请求并获取响应。这个例子展示了HttpClient库的基本用法,实际...

    (完整版)JAVA利用HttpClient进行POST请求(HTTPS).doc

    JAVA HttpClient是Apache软件基金会提供的一个开源实现HTTP客户端的Java库,能够帮助开发者轻松地与HTTP服务器进行交互。在实际项目中,我们经常需要使用HttpClient来发送POST请求,以便与服务器进行数据交换。但是...

    java,HttpClient模拟上传,绕过SSL认证

    在Java编程中,HttpClient库是Apache提供的一款强大的HTTP客户端工具,用于执行HTTP和HTTPS请求。在某些场景下,比如开发测试或调试时,我们可能需要模拟上传文件到HTTPS服务器,而这个过程可能会遇到SSL(Secure ...

    java.net.URLConnection发送HTTP请求与通过Apache HttpClient发送HTTP请求比较

    此外,HttpClient的维护和升级并不总是与Java版本同步,可能导致兼容性问题。 总结来说,`java.net.URLConnection`适合简单、轻量级的HTTP请求,而Apache HttpClient更适合需要处理复杂HTTP逻辑和高性能需求的场景...

    commons-httpclient-3.0.jar JAVA中使用HttpClient可以用到

    《JAVA中使用HttpClient:commons-httpclient-3.0.jar详解》 在JAVA开发中,进行HTTP请求时,Apache的HttpClient库是一个不可或缺的工具。本文将深入解析`commons-httpclient-3.0.jar`,它是HttpClient的一个重要...

    java使用HttpClient发送http请求

    “工具”标签表明HttpClient是一个实用工具,可以与其他Java项目集成,提高开发效率。在实际项目中,你可能需要结合其他库,如Jackson或Gson处理JSON数据,或者使用OkHttp等替代方案。 在提供的文件`HttpTest`中,...

    Java-HttpClient帮助文档

    通过理解和掌握HttpClient的使用,开发者能够更好地实现与HTTP服务器的交互,处理复杂的网络任务。查阅httpclient-4.5.2-javadoc文档,可以获得更详细的方法和类的解释,进一步提升HttpClient的使用技巧。

    JAVA中三种URL连接方法

    本文将深入探讨JAVA中三种常见的URL连接方法,即使用`URL`类的`openConnection()`方法、使用`HttpURLConnection`类,以及采用`HttpClient`库进行网络请求。 #### `URL`类及其使用 `URL`类是JAVA中用于表示统一资源...

    httpclient方式调用url

    本篇文章将深入探讨如何使用HttpClient方式调用URL,以及相关的知识点。 首先,HttpClient允许我们构建复杂的HTTP请求,包括GET、POST以及其他HTTP方法。使用HttpClient调用URL的基本步骤包括创建HttpClient实例、...

    java HttpClient 发送GET请求和带有表单参数的POST请求教程例子

    ### Java HttpClient 发送GET请求和带有表单参数的POST请求详解 ...通过上述示例和解释,你应该能够理解和掌握如何使用Java HttpClient库来发送GET和POST请求,这对于开发Web应用程序或与API接口交互至关重要。

    commons-httpclient,java中使用httpclient中使用的扩展工具

    1. **连接管理**:HttpClient提供了`HttpConnectionManager`接口,用于管理与远程服务器的连接。默认实现`SingleClientConnManager`适用于单线程或短连接的应用,而`MultiThreadedHttpConnectionManager`则适合多...

Global site tag (gtag.js) - Google Analytics