java url与httpclient

Using the java client to access the website is a necessary skill for programmers, and the default java package java.net supports it

 

package Http.client;

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

/**
 * Class description Use the net class of the official website for testing
 *
 * @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 ();
		}
	}
}

 

The method of get request and address splicing is used here. If you use post request, you need to set the header.

 

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;

/**
 * class description
 *
 * @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 = "Transmitted data";
			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 ();
		}
	}
}

 

It is very troublesome to observe the code, so refer to 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;

/**
 * class description
 *
 * @author rfk
 */
public class TestHttpClientGet {
	public static void main(String[] args) {
		// If String url="www.baidu.com"; there will be an error
		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 ();
			}
		}
	}
}

 

If it is a post request, the code is as follows

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;

/**
 * class description
 *
 * @author rfk
 */
public class TestHttpClientPost {
	public final static String url = "http://www.baidu.com";
	// The address to be accessed
	public static void main(String[] args) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// Create a client for HTTP access
		HttpPost httpPost = new HttpPost(url);
		// Now about to send a post request NameValuePair is an interface
		List<NameValuePair> allParams = new ArrayList<NameValuePair>();
		// All request parameters need to be processed in a package
		// public class BasicNameValuePair implements NameValuePair
		allParams.add(new BasicNameValuePair("msg", "Hello world!"));
		// Append the passed parameters
		allParams.add(new BasicNameValuePair("mid", "helloworld"));
		// Append the passed parameters
		// Since Chinese is now passed, it is necessary to control encoding for Chinese
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(allParams, "UTF-8");// Set Baini Ma
		httpPost.setEntity(entity);
		// Bind the data to be sent with the POST request object
		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);
		}
	}
}

If you need to upload files in the java client section

 

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 to upload
		File file = new File("D:" + File.separator + "dog.jpg");
		//path
		String url = "http://www.baidu.com";
		// Create an HttpClient action class
		HttpClient httpClient = HttpClients.createDefault();
		//create post
		HttpPost httpPost = new HttpPost(url);
		// If you want to upload files, you must use "multipart/form-data" to set
		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(); // Define upload entity class
		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost); // Send post request
		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()));
	}
}

 

The following code tools are reproduced from 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;

/**
 * class description
 *
 * @author rfk
 */
public class HttpClientUtil {

	public static String doGet(String url, Map<String, String> param) {
		// Create Httpclient object
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// Jian Jian uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build ();
			// Create http GET request
			HttpGet httpGet = new HttpGet(uri);
			// execute the request
			response = httpclient.execute(httpGet);
			// Determine if the return status is 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) {
		// Create Httpclient object
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// Create Http Post request
			HttpPost httpPost = new HttpPost(url);
			// create parameter list
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// mock form
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			// execute the http request
			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) {
		// Create Httpclient object
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// Create Http Post request
			HttpPost httpPost = new HttpPost(url);
			// create request content
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// execute the http request
			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;
	}
}

 

 Upload the code to github: https://github.com/sona0402/url-httpclient.git

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326753160&siteId=291194637