HttpClient,POST 접근 사용 하기

2728 단어 Java
1.httpclient 4.5 의 jar 패키지 가 필요 합 니 다.
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
2.코드
        List formparams = new ArrayList(); 
        //     
        formparams.add(new BasicNameValuePair("username", ""));  
        formparams.add(new BasicNameValuePair("password", ""));  
        HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "utf-8");  
    
        RequestConfig requestConfig = RequestConfig.custom()  
        .setConnectTimeout(5000)// 、    :connectionTimeout-->       url         
                .setSocketTimeout(5000)//  、      :SocketTimeout-->        url,  response         
                .setConnectionRequestTimeout(5000)  
                .build();  
    
        HttpClient client = new DefaultHttpClient();  
        //  post    url
        HttpPost post = new HttpPost("http://cnivi.com.cn/login");  
        post.setEntity(reqEntity);  
        post.setConfig(requestConfig);  
        HttpResponse response = client.execute(post);  
    
        if (response.getStatusLine().getStatusCode() == 200) {  
            HttpEntity resEntity = response.getEntity();  
            // message       
            String message = EntityUtils.toString(resEntity, "utf-8");  
            System.out.println(message);  
        } else {  
            System.out.println("    ");  
        } 

3.중국어 난동 이 발생 하면 다음 코드 를 사용 해 보 세 요.
public static String post(String json,String URL) { //json:  url   
	  String obj=null;
      //      httpClient   
      CloseableHttpClient httpclient = HttpClients.createDefault();  
      //   httppost    
      HttpPost httppost = new HttpPost(URL);  
      httppost.addHeader("Content-type", "application/json; charset=utf-8");
      httppost.setHeader("Accept", "application/json");
    try {  
    	StringEntity strEntity = new StringEntity(json,Charset.forName("UTF-8"));  //       ,      
    	strEntity.setContentEncoding("UTF-8");
    	httppost.setEntity(strEntity);
        CloseableHttpResponse response = httpclient.execute(httppost);  
        try {  
        	//      
            HttpEntity entity = response.getEntity();  
            if (entity != null) {  
            	obj=EntityUtils.toString(entity, "UTF-8");
            }  
            
        } finally {  
            response.close();  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    }finally {  
        //     ,     
        httpclient.close();  
    }  
    return obj;
}

좋은 웹페이지 즐겨찾기