HttpClient 4.5 게시 요청 보 내기

5734 단어 자바
HttpClient 4.5 post 요청 예제 코드 보 내기
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Test {

    public static void main(String args[]){

            String  url = "    ";
            //          
            HttpClient httpClient = HttpClientBuilder.create().build();
              //       post  
            HttpPost request = new HttpPost(url);
            try {

                //    post  
                List postData = new ArrayList();
                postData.add(new BasicNameValuePair("username","user"));
                postData.add(new BasicNameValuePair("password","ps"));
                request.setEntity(new UrlEncodedFormEntity(postData));

                //             
                 HttpResponse response = httpClient.execute(request);
                 //             (0--200    )
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                        //      
                        String result = EntityUtils.toString(response.getEntity(),"utf-8");
                        System.out.println(result);
                   } 



            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

}

좋은 웹페이지 즐겨찾기