HttpGet &&HttpPost方法发送header,params, Content

  public static JSONObject post(String url,JSONObject json,Map headers){  
		     HttpClient client = new DefaultHttpClient();  
		     HttpPost post = new HttpPost(url);  
		     JSONObject response = null;  
		    post.setHeader("Content-Type", "application/json");
				if (headers != null) {
					Set keys = headers.keySet();
					for (Iterator i = keys.iterator(); i.hasNext();) {
						String key = (String) i.next();
						post.addHeader(key, headers.get(key));
						
					}
				}
				
			 
		     try {  
//		    	 json = new JSONObject();
//		    	 json.put("Email", "[email protected]");;
//		    	 json.put("Password", "123456");
		         StringEntity s = new StringEntity(json.toString(),"utf-8");  
		         s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
		         //s.setContentType("application/json");  
		         //s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
		         post.setEntity(s);  
		            
		         // HttpResponse res = client.execute(post);  
		      	HttpResponse httpResponse = client.execute(post);
				InputStream inStream =     httpResponse.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));  
				StringBuilder strber = new StringBuilder();  

				String line = null;  
				while ((line = reader.readLine()) != null)   
					strber.append(line + "\n");  
				inStream.close();  
				Log.i("MobilpriseActivity", strber.toString());
		          if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
		              HttpEntity entity = httpResponse.getEntity();  
		              String charset = EntityUtils.getContentCharSet(entity);  
		            //  response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));  
		          }  
		      } catch (Exception e) {  
		          throw new RuntimeException(e);  
		      }  
		      return response;  
		  }  

Get方法发送header

	/**
	 * get 
	 * @param url
	 * @param headerKey
	 * @param headerVaue
	 */
	private void getHttp(String url,Map headers){
		httpGet = new HttpGet(url); 
		  
		if (headers != null) {
			Set keys = headers.keySet();
			for (Iterator i = keys.iterator(); i.hasNext();) {
				String key = (String) i.next();
				httpGet.addHeader(key, headers.get(key));
			}
		}
		
		
		HttpParams httpParameters = new BasicHttpParams();  
		HttpConnectionParams.setConnectionTimeout(httpParameters,  
				timeoutConnection);  
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);  

		HttpClient httpclient = new DefaultHttpClient(httpParameters); 
		try {
			HttpResponse httpResponse = httpclient.execute(httpGet);
			InputStream inStream =     httpResponse.getEntity().getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));  
			StringBuilder strber = new StringBuilder();  
			String line = null;  
			while ((line = reader.readLine()) != null)   
				strber.append(line + "\n");  
			inStream.close();  
			Log.i("MobilpriseActivity", strber.toString());
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
				Log.i("MobilpriseActivity", "success");
			}   
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}

HttpPost发送header与Parameters

/**
	 * 
	 * @param url the web will be connected 
	 * @param headers 
	 * @param parmas data will be sent
	 */
	private void postHttp(String url,Map headers,Map parmas){
		httpPost = new HttpPost(url);  

		if (headers != null) {
			Set keys = headers.keySet();
			for (Iterator i = keys.iterator(); i.hasNext();) {
				String key = (String) i.next();
				httpPost.addHeader(key, headers.get(key));
			}
		}
		ArrayList pairs = new ArrayList();
		if (parmas != null) {
			Set keys = parmas.keySet();
			for (Iterator i = keys.iterator(); i.hasNext();) {
				String key = (String) i.next();
				pairs.add(new BasicNameValuePair(key, parmas.get(key)));
			}
		}

		HttpParams httpParameters = new BasicHttpParams();  
		HttpConnectionParams.setConnectionTimeout(httpParameters,  
				timeoutConnection);  
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);  

		HttpClient httpclient = new DefaultHttpClient(httpParameters); 


		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8")); // 
			HttpResponse httpResponse = httpclient.execute(httpPost);
			InputStream inStream =     httpResponse.getEntity().getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));  
			StringBuilder strber = new StringBuilder();  
			String line = null;  
			while ((line = reader.readLine()) != null)   
				strber.append(line + "\n");  
			inStream.close();  
			Log.i("MobilpriseActivity", strber.toString());
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
				Log.i("MobilpriseActivity", "success");
			

			}  


		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

HttpPost发送header, parameters ,Content(json格式)

此处特别注意,发送的header 与Content的格式都是Content-Type: application/json

利用HttpPost发送的第二种方法与前面一种相关,注释掉post.setHeader("Content-Type", "application/json");把 s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));改为 s.setContentEncoding("HTTP.UTF_8");看代码

  public static JSONObject post(String url,JSONObject json,Map headers){  
		     HttpClient client = new DefaultHttpClient();  
		     HttpPost post = new HttpPost(url);  
		     JSONObject response = null;  
		   // post.setHeader("Content-Type", "application/json");
				if (headers != null) {
					Set keys = headers.keySet();
					for (Iterator i = keys.iterator(); i.hasNext();) {
						String key = (String) i.next();
						post.addHeader(key, headers.get(key));
						
					}
				}
				
			 
		     try {  
		    	 json = new JSONObject();
		    	 json.put("Email", "[email protected]");;
		    	 json.put("Password", "123456");
		         StringEntity s = new StringEntity(json.toString(),"utf-8");  
		       //  s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
		         s.setContentEncoding("HTTP.UTF_8");
		         //s.setContentType("application/json");  
		         s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
		         post.setEntity(s);  
		            
		         // HttpResponse res = client.execute(post);  
		      	HttpResponse httpResponse = client.execute(post);
				InputStream inStream =     httpResponse.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));  
				StringBuilder strber = new StringBuilder();  
				String line = null;  
				while ((line = reader.readLine()) != null)   
					strber.append(line + "\n");  
				inStream.close();  
				Log.i("MobilpriseActivity", strber.toString());
		          if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
		              HttpEntity entity = httpResponse.getEntity();  
		              String charset = EntityUtils.getContentCharSet(entity);  
		            //  response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));  
		          }  
		      } catch (Exception e) {  
		          throw new RuntimeException(e);  
		      }  
		      return response;  
		  } 






你可能感兴趣的:(android)