자바에서post를 통해 백엔드 서버에 접근하는 방법

3479 단어 javapost
최근 자바 학습에서post 방식으로 백엔드 서버에 접근하고 있습니다. 그럼 오늘도 학습 노트라고 할 수 있습니다!
먼저 위의 코드:

Runnable payRunnable = new Runnable()  
      { 
        @Override 
        public void run()  
        { 
          try 
          {   
            HashMap<String, String> payParamMap = new HashMap<String, String>(); 
            payParamMap.put("canshu" ,"woshicanshu" ); 
            String payParamStr = XmlUtils.toXml(payParamMap);// xml  
             
            String resultStr = Utils.httpPost(UrlString, payParamStr);//  
             
            //<span style="font-family: Arial, Helvetica, sans-serif;">resultStr   </span> 
          } 
          catch(Exception e) 
          { 
            e.printStackTrace(); 
          } 
        } 
      }; 
      //   
      Thread payThread = new Thread(payRunnable); 
      payThread.start(); 
다음 코드:

public class Utils { 
  private static final String TAG = "woshiTag"; 
 
  public static String httpPost(String url, String entity) { 
    if (url == null || url.length() == 0) { 
      Log.e(TAG, "httpPost, url is null"); 
      return null; 
    } 
     
    HttpClient httpClient = getNewHttpClient(); 
     
    HttpPost httpPost = new HttpPost(url); 
     
    try { 
      httpPost.setEntity(new StringEntity(entity, HTTP.UTF_8)); 
      httpPost.setHeader("Accept", "application/json"); 
      httpPost.setHeader("Content-type", "application/json"); 
       
      HttpResponse resp = httpClient.execute(httpPost); 
      if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { 
        Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode()); 
        return null; 
      } 
 
      return new String(EntityUtils.toByteArray(resp.getEntity())); 
    } catch (Exception e) { 
      Log.e(TAG, "httpPost exception, e = " + e.getMessage()); 
      e.printStackTrace(); 
      return null; 
    } 
  } 
  private static HttpClient getNewHttpClient() {  
      try {  
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
        trustStore.load(null, null);  
 
        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);  
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
 
        HttpParams params = new BasicHttpParams();  
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
 
        SchemeRegistry registry = new SchemeRegistry();  
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
        registry.register(new Scheme("https", sf, 443));  
 
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);  
 
        return new DefaultHttpClient(ccm, params);  
      } catch (Exception e) {  
        return new DefaultHttpClient();  
      }  
    } 
}
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기