在java程序開發中經常用到與服務端的交互工作,主要的就是傳遞相應的參數請求從而獲取到對應的結果加以處理
可以使用Get請求與Post請求,注意!這里的Get請求不是通過瀏覽器界面而是在程序代碼中設置的,達到Get請求的目的,具體請詳見下列描述
以下get與post請求需要引入的包:
import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; 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.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;
Get請求:
/** * 正常簡易的使用HttpGet來向服務端發送Get請求傳遞的參數直接在url后面拼裝上就可以了 * @param httpUrl */ public static String httpGet(String httpUrl){ httpUrl ="http://192.168.199.138/weixin/test.php?appid=appidaaaa&secret=secretbbbb"; HttpGet httpGet = new HttpGet(httpUrl); CloseableHttpResponse chResponse = null; String result = null; try { chResponse = HttpClients.createDefault().execute(httpGet); if(chResponse.getStatusLine().getStatusCode()==200){ result = EntityUtils.toString(chResponse.getEntity()); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(chResponse !=null){ try { chResponse.close(); } catch (IOException e) { e.printStackTrace(); } } } if(result !=null){ System.out.println("有結果返回result=="+result); return result; }else{ System.out.println("請求沒有結果返回"); return ""; } } /** * 顯示的來調用HttpGet這里的發送執行execut與上面簡易方法有不同, * 傳遞的參數直接拼裝在url上傳遞即可 * @param httpUrl * @return */ @SuppressWarnings("deprecation") public static String httpGetShow(String httpUrl){ //httpUrl = ""; DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response =null; String result = null; try { //發送get請求 HttpGet httpGet = new HttpGet(httpUrl); //不同之處 response= client.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(response.getEntity()); httpUrl = URLDecoder.decode(httpUrl, "UTF-8"); } } catch (IOException e) { e.printStackTrace(); }finally { client.close(); } if(result !=null){ return result; }else{ return ""; } }
Post請求:
/** * 不顯示的使用HttpPost就會默認提交請求的方式為post, * 傳遞的參數為以key:value的形式來傳遞參數 * @param httpUrl * @param imagebyte 可以傳遞圖片等文件,以字節數組的形式傳遞 */ @SuppressWarnings({ "deprecation" }) public static String httpPost(String httpUrl,byte[] imagebyte){ httpUrl="http://192.168.199.138/weixin/test.php"; HttpPost httpPost = new HttpPost(httpUrl); ByteArrayBody image = new ByteArrayBody(imagebyte,ContentType.APPLICATION_JSON,"image.jpg");//傳遞圖片的時候可以通過此處上傳image.jpg隨便給出即可 String appid = "appid"; String secret = "secret"; StringBody appidbody = new StringBody(appid,ContentType.APPLICATION_JSON); StringBody secretbody = new StringBody(secret,ContentType.APPLICATION_JSON); MultipartEntityBuilder me = MultipartEntityBuilder.create(); me.addPart("image", image)//image參數為在服務端獲取的key通過image這個參數可以獲取到傳遞的字節流,這里不一定就是image,你的服務端使用什么這里就對應給出什么參數即可 .addPart("appid",appidbody ) .addPart("secret", secretbody); DefaultHttpClient client= new DefaultHttpClient(); HttpEntity reqEntity = me.build(); httpPost.setEntity(reqEntity); HttpResponse responseRes = null; try { responseRes=client.execute(httpPost); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { client.close(); } int status = responseRes.getStatusLine().getStatusCode(); String resultStr =null; if (status == 200) { byte[] content; try { content = getContent(responseRes); resultStr = new String(content,"utf-8"); System.out.println("httpPost返回的結果==:"+resultStr); } catch (IOException e) { e.printStackTrace(); } } if(resultStr !=null){ return resultStr; }else{ return ""; } } /** * 顯示的調用HttpPost來使用post方式提交請求,並且將請求的參數提前拼裝成json字符串, * 直接使用StringEntity來發送參數不必要再使用key:value的形式來設置請求參數, * 在服務端使用request.getInputStream()來把request中的發送過來的json字符串解析出來, * 就是因為使用StringEntity來包裝了傳遞的參數 * @param httpUrl * @param jsonParam */ @SuppressWarnings({ "resource", "deprecation" }) public static String httpPostShow(String httpUrl,String jsonParam){ httpUrl="http://192.168.199.138/weixin/test.php"; jsonParam="{\"appid\":\"appidbbbb33333\",\"secret\":\"secretaaaaa3333\"}";//拼裝一個json串 DefaultHttpClient httpClient = new DefaultHttpClient(); //這里就是顯示的調用post來設置使用post提交請求 HttpPost method = new HttpPost(httpUrl); String result = null; try { if (null != jsonParam) { //解決中文亂碼問題 StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");//這個StringEntity可以在服務端不用key:value形式來接收,可以request.getInputStream()來獲取處理整個請求然后解析即可 entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity); } HttpResponse response = httpClient.execute(method); httpUrl = URLDecoder.decode(httpUrl, "UTF-8"); if (response.getStatusLine().getStatusCode() == 200) { try { result = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } if(result !=null){ return result; }else{ return ""; } } private static byte[] getContent(HttpResponse response) throws IOException { InputStream result = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); try { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = resEntity.getContent(); int len = 0; while ((len = result.read()) != -1) { out.write(len); } return out.toByteArray(); } } catch (IOException e) { e.printStackTrace(); throw new IOException("getContent異常", e); } finally { out.close(); if (result != null) { result.close(); } } return null; }
以上為java中http的get與post請求方式,httpPost(String httpUrl,byte[] imagebyte)這個方法可以傳遞圖片等非結構化數據,以流的形式傳遞。