JAVA

자바로 POST 방식으로 통신하기, java httppost 클래스를 활용한 예제

nineDeveloper 2014. 2. 3. 11:14
728x90
반응형

출처 - http://stackoverflow.com/questions/3324717/sending-http-post-request-in-java

 

예제1:

/*
 * Create the POST request
 */
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
/*
 * Making HTTP Request
 */
try {
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity respEntity = response.getEntity();

    if (respEntity != null) {
        // EntityUtils to get the reponse content
        String content =  EntityUtils.toString(respEntity);
    }
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}

예제 2:

String rawData = "id=10"; String type = "application/x-www-form-urlencoded"; String encodedData = UrlEncoder.encode( rawData ); URL u = new URL("http://www.example.com/page.php"); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true); conn.setRequestMethod( "POST" ); conn.setRequestProperty( "Content-Type", type ); conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length())); OutputStream os = conn.getOutputStream(); os.write( encodedData.getBytes() );

 

그리고 첨부파일로 등록한 jar 는 이 사이트에서 대부분 다운로드 받았다.

URL - http://www.java2s.com/Code/Jar/h/Downloadhttpcore40jar.htm

728x90
반응형