java httpclient POST和GET請求 傳送JSON
阿新 • • 發佈:2019-01-10
第一步導包
匯入的jar包有 1:httpclient 2:httpcore 3commons-logging-api 4:json包 (轉換json的jar包是很多的每個系統的方法都是不一樣) json-io-4.3.0
第二步 寫程式碼
GET請求
public static void doGet(String url) throws Exception{ //url 路徑 HttpClient client = new DefultHttpClient(); HttpGet getmeth = new HttpGet(url); try { HttpResponse statueCode = cleint.execute(getmeth); System.out.println(response1.getStatusLine());//狀態碼 200成功 500伺服器內部報錯這個時候要看服務端的報錯日誌 404 路徑錯誤 }catch(IOException e){ e.printStackTrace(); } }
POST請求
public static void doPost(String url,String param) throws Exception{ HttpClient client = new DefultHttpClient(); HttpPost postmeth = new HttpPost(url); postmeth.setEntity(new StringEntity(param)); //post請求引數 param可以在請求之前進行json轉換 try{ HttpResponse statueCode = cleint.execute(getmeth); System.out.println(response1.getStatusLine());//狀態碼 200成功 500伺服器內部報錯這個時候要看服務端的報錯日誌 404 路徑錯誤 }catch(IOException e){ e.printStackTrace(); } }
轉json方法
public static String json( String param){
List<String> list = new ArrayList<String>();
list.add(param);
String json = JsonWriter.objectToJson(list)'
return json;
}
main方法呼叫請求
public static void main(String[] args) { json(param); try { doGet(url); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { doPost(url ,param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
webservice 基礎知識