Network request framework----HttpClient's get, post and image upload server

HttpClient is a sub-project under Apache Jakarta Common, which is used to provide an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest version and recommendations of the HTTP protocol. HttpClient has been used in many projects, such as Cactus and HTMLUnit, two other well-known open source projects on Apache Jakarta, both use HttpClient.

HttpClient: is an interface.

characteristic:

1. Based on standard, pure java language. Implemented Http1.0 and Http1.1

2. Implements all Http methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible object-oriented structure.

3. Support HTTPS protocol.

4. Establish a transparent connection through Http proxy.

5. Use the CONNECT method to establish a tunneled https connection through the Http proxy.

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos authentication scheme.

7. Plug-in custom authentication scheme.

8. Portable and reliable socket factory makes it easier to use third-party solutions.

9. The connection manager supports multi-threaded applications. Supports setting the maximum number of connections, and supports setting the maximum number of connections per host, and discovers and closes expired connections.

10. Automatically handle cookies in Set-Cookie.

11. Plug-in custom cookie policy.

12. The output stream of Request can avoid direct buffering of the content in the stream to the socket server.

13. The input stream of Response can effectively read the corresponding content directly from the socket server.

14. Use KeepAlive to maintain persistent connections in http1.0 and http1.1.

15. Get the response code and headers sent by the server directly.

16. Ability to set connection timeout.

17. Experimental support for http1.1 response caching.

18. The source code is freely available under the Apache License.

Case renderings:

MainActivity.java

 

public class MainActivity extends Activity implements OnClickListener {

	public static String urls = "http://gpj.zhangwoo.cn/app.php?platform=android&appkey=5a379b5eed8aaae531df5f60b12100cfb6dff2c1";

	private TextView mTextView;
	private ImageView imagegvoew;
	String resultStr = "";
	String resultStr1 = "";
	private Bitmap mBitmap = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		findViewById(R.id.btn3).setOnClickListener(this);
		findViewById(R.id.btn4).setOnClickListener(this);
		mTextView = (TextView) findViewById(R.id.Text);
		imagegvoew = (ImageView) findViewById(R.id.imagegvoew);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn1:

			Thread visitBaiduThread = new Thread(new VisitWebRunnable());
			visitBaiduThread.start();
			try {
				visitBaiduThread.join();
				if (!resultStr.equals("")) {
					mTextView.setText(resultStr);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}

			break;
		case R.id.btn2:
			Thread visitBaiduThreads = new Thread(new VisitWebRunnables());
			visitBaiduThreads.start();
			try {
				visitBaiduThreads.join();
				if (!resultStr1.equals("")) {
					mTextView.setText(resultStr1);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
			break;
		case R.id.btn3:

			new DownImgAsyncTask()
					.execute("http://avatar.csdn.net/8/6/0/2_dickyqie.jpg");

			break;
		case R.id.btn4:
			//Util.addFile("url");//Image path
			break;
		default:
			break;
		}

	}

	/** Rewrite the handleMessage method here to update the UI after receiving the child thread data **/
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// closure
				imagegvoew.setImageBitmap (mBitmap);
				break;
			}
		}
	};

	class DownImgAsyncTask extends AsyncTask<String, Void, Bitmap> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();

		}

		@Override
		protected Bitmap doInBackground(String... params) {
			// TODO Auto-generated method stub
			Bitmap b = Util.getImageBitmap(params[0]);
			return b;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				imagegvoew.setImageBitmap (result);
			}
		}

	}

	/***
	 * get
	 *
	 * @author zq
	 *
	 */
	class VisitWebRunnable implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			HttpClient httpCLient = new DefaultHttpClient();
			// create a get request instance
			HttpGet httpget = new HttpGet("http://www.baidu.com");
			try {
				HttpResponse response = httpCLient.execute(httpget);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

					String result = EntityUtils.toString(response.getEntity(),
							"UTF-8");
					resultStr = result;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}

		}

	}

	/***
	 * Post
	 *
	 * @author zq
	 *
	 */
	class VisitWebRunnables implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("c", "member"));
			formparams.add(new BasicNameValuePair("a", "getdepartments"));
			HttpClient client = null;
			HttpPost request = null;
			try {
				client = new DefaultHttpClient();
				request = new HttpPost(urls);
				request.setEntity(new UrlEncodedFormEntity(formparams,
						HTTP.UTF_8));
				HttpResponse response = client.execute(request);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					String result = EntityUtils.toString(response.getEntity(),
							"UTF-8");
					System.out.println(result);
					resultStr1 = result;
				}
			} catch (IOException e) {
				e.printStackTrace ();

			}

		}

	}

}

 

public class Util {
	/**
	 * Image loading
	 *
	 * @param url
	 * @return
	 */
	public static Bitmap getImageBitmap(String url) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		try {
			HttpResponse resp = httpclient.execute(httpget);
			// Determine if it is executed correctly
			if (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode()) {
				// Convert the returned content to bitmap
				HttpEntity entity = resp.getEntity();
				InputStream in = entity.getContent();
				Bitmap mBitmap = BitmapFactory.decodeStream(in);
				// Send a message to the handler to perform the display image operation
				return mBitmap;
			}

		} catch (Exception e) {
		} finally {
			httpclient.getConnectionManager().shutdown();
		}

		return null;
	}

	/***
	 * upload files
	 */
	public static void addFile(String url) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost(url);

			FileBody bin = new FileBody(new File(url));
			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);
			try {
				System.out.println(response.getStatusLine());
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					System.out.println("Response content length: "
							+ resEntity.getContentLength());
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace ();
		} catch (IOException e) {
			e.printStackTrace ();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace ();
			}
		}
	}
}


Remember to add network permissions

 

<uses-permission android:name="android.permission.INTERNET"/>

 

To complete the above functions, you need httpclient.jarhttpcore.jar   htttpmime.jar and click to download

 

Source code download: http://download.csdn.net/detail/dickyqie/9707202

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326313263&siteId=291194637