상세 컨텐츠

본문 제목

안드로이드 자바 URL get, post 방식 connect 관련

스마트기기개발관련/안드로이드 개발

by AlrepondTech 2020. 9. 21. 02:46

본문

반응형

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

출처: http://stackoverflow.com/questions/5166143/how-to-get-content-of-a-url-and-to-read-it-in-a-android-java-application-using-e

 

//Following code works fine but read's the source code as well as the content, I just need to read the content Thanks for the help.//

package t.n.e;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.xml.sax.Parser;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;



public class urlgettingproject extends Activity {
    private EditText T1;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        T1 = (EditText)findViewById(R.id.T1);
        StringBuilder content = new StringBuilder();


        try {
            URL url = new URL("http://10.0.22.222:8080/SaveName.jsp?first=12&second=12&work=min");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                content.append(str +"\n");
                T1.setText(content);
            }
            in.close();
        } catch (MalformedURLException e){
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

well, if you just need the content, why won't you simplify it this way:

private InputStream OpenHttpConnection(String strURL)
            throws IOException {
        URLConnection conn = null;
        InputStream inputStream = null;
        URL url = new URL(strURL);
        conn = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpConn.getInputStream();
        }
        return inputStream;
    }

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://developer.android.com/reference/java/net/URLConnection.html

public abstract class

URLConnection

extends Object

java.lang.Object
   ↳ java.net.URLConnection
Known Direct SubclassesHttpURLConnectionJarURLConnection
Known Indirect SubclassesHttpsURLConnection

Class Overview


A connection to a URL for reading or writing. For HTTP connections, see HttpURLConnection for documentation of HTTP-specific features.

For example, to retrieve ftp://mirror.csclub.uwaterloo.ca/index.html:

   URL url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
   
URLConnection urlConnection = url.openConnection();
   
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
   
try {
     readStream
(in);
   
finally {
     
in.close();
   
}
 
}

URLConnection must be configured before it has connected to the remote resource. Instances of URLConnection are not reusable: you must use a different instance for each connection to a resource.

Timeouts

URLConnection supports two timeouts: a connect timeout and a read timeout. By default, operations never time out.

Built-in Protocols

  • File
    Resources from the local file system can be loaded using file: URIs. File connections can only be used for input.
  • FTP
    File Transfer Protocol (RFC 959) is supported, but with no public subclass. FTP connections can be used for input or output but not both.By default, FTP connections will be made using anonymous as the username and the empty string as the password. Specify alternate usernames and passwords in the URL: ftp://username:password@host/path.
  • HTTP and HTTPS
    Refer to the HttpURLConnection and HttpsURLConnection subclasses.
  • Jar
    Refer to the JarURLConnection subclass.

Registering Additional Protocols

Use setURLStreamHandlerFactory(URLStreamHandlerFactory) to register handlers for other protocol types.

 

 

=================================

=================================

=================================

 

 

 

출처: http://www.androidside.com/bbs/board.php?bo_table=B49&wr_id=75281

 

안녕하세요
안드로이드 c2dm이용해서 메시지 전송을 하려고 합니다.
3rd파티 앱서버로 registration ID를 전송하고
서버에서는 전송받은 registration ID를 db에 저장하려고 합니다.
그런데 왜...ㅠㅠㅠㅠㅠㅠㅠ get방식으로 메시지를 전송하려고 하는데
전송이 안됩니다.


아래 코드에 문제가 있나요??
그냥 웹브라우저에 아래같이 직접 url을 입력하면 서버쪽에서는 분명 잘 동작하는데...ㅠ 뭐가문제인가요?


http://http://192.168.123.106/ttserver.php?registration_id=APA91bFM_vyDnpkHKc5u62dwryd5hJa8dGzD_E5vWBqwkwb6byNP0hqeD_gaIu4-Ne5pFOCpuWY6LgxhIt1fi7APLfjZsSW2bdbKm7beCFcJNqhyaSOqmEunpI2sOtudFsOgp1EXW3BwXCkWNchKzjTLhGvj4CMiQQ&tel=01056361305&mode=register   


 public void send(String my_role) throws Exception{
  
  try {
   URL idRegistrationUrl = new URL(
     "http://192.168.123.106/ttserver.php?tel=" + tel
     + "&message=" + my_role + "&mode=send" );
   HttpURLConnection conn = (HttpURLConnection) idRegistrationUrl.openConnection();
   conn.setConnectTimeout(60000);
   conn.setReadTimeout(60000);
   conn.setUseCaches(false);
   Log.i("tag", "idRegistrationUrl = " + idRegistrationUrl.toString());


   // URL에 접속
   //  InputStream is = conn.getInputStream();
   //  is.close();
   conn.disconnect();


   Toast toast_reg = Toast.makeText(this, "메시지 전송", Toast.LENGTH_SHORT);
   toast_reg.show();

  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }


---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

저도 이런 문제가 발생되었는데 ..... 인터넷에서 찾아보니깐 모 스레드 설정을 해줘야 한다고 하더라구요.ㅠㅠ

저도 스레드 설정에 대해서는 모르겠네요..ㅠㅠ 다른 고수 분이 스레드 설정법좀 답변해주시면 좋을려만..ㅠㅠ

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

wr.write(param);

wr.flush();

파라메터를 보내보세요.... param은 파라메터 스트링입니다.

안된다면 HttpURLConnection말고 httpClient를 사용해보세요

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

올려주신 URL과 설정하는 URL이 다르네요 ㄱ- 

registration_id 이건어디간거임 

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

그럼 Post로 하세요

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

=================================

=================================

=================================

 

 

 

출처: http://cafe.daum.net/KHHECK/Qfqu/159?docid=1G20AQfqu15920100419143027r

 자바어플리케이션에서 get 방식으로 asp 호출하는 방법- ★안드로이드★

★안드로이드★ -자바어플리케이션(XX.java)에서 get 방식으로 asp 호출하는 방법좀 가르쳐주세요

<답변>

간단한 방법을 알려드리죠.

자카르타 프로젝트 중 HttpClient에 관련된 프로젝트가 있습니다.

이 프로젝트가 무언고 하면 웹브라우저의 기능을 하는 라이브러리를 개발하는 것이죠.

이것을 사용하면 get/post(multi-part 포함) 모두 간단하게 호출할 수 있습니다.

get방식으로 특정 URL을 호출하는 방법을 간략한 예제로 만들어봤습니다.(JDK 1.4 문법)

URL은 asp, aspx, jsp, html 뭐든 상관 없습니다. http://로 시작하는 URL이면 뭐든 가능합니다.

public void get(String url) {

HttpClient client = new HttpClient();

GetMethod method = new GetMethod(url);

try {

client.getParams()

.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

client.getHttpConnectionManager()

.getParams().setConnectionTimeout(5000);

NameVal‍uePair nvp1 = new NameVal‍uePair("param1", "value1");

NameVal‍uePair nvp2 = new NameVal‍uePair("param2", "value2");

method.setQueryString(new NameVal‍uePair[]{nvp1, nvp2});

int status = client.executeMethod(method);

if (status == HttpStatus.SC_OK) {

BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

StringBuffer buf = new StringBuffer();

String s = null;

while (null != (s = br.readLine())) {

buf.append(s);

}

br.close();

System.out.println(buf);

} else {

System.err.println(HttpStatus.getStatusText(status));

}

} catch (Exception ex) {

} finally {

method.releaseConnection();

}

}

 

 

=================================

=================================

=================================

 

 

출처: http://bluexmas.tistory.com/328

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;


public class HttpGetCall {


    public static void main(String[] args) throws Exception {
        URL url = new URL("http://naver.com");
        InputStream is = url.openStream();


        BufferedReader inFile = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while( (line = inFile.readLine()) != null ) {
            System.out.println(line);
        }
        is.close();
    }
}

GETHTTPJavaURL

 

 

=================================

=================================

=================================

 

 

출처: http://ggoreb.tistory.com/114


java.net.URLConnection

- URL 내용을 읽어오거나, URL 주소에 GET / POST로 데이터를 전달 할 때 사용함
- 웹 페이지나 서블릿에 데이터를 전달 수  있음
- URL --> openConnection() --> URLConnection  --> getInputStream --> InputStream (내용읽음)
- URL 의 OpenStream() : URL의 입력 스트림만 개설 (차이점)
- URLConnection : URL의 입력, 출력 스트림 개설

Construct 
protected URLConnection(URL) : 직접 생성 불가능 , OpenConnection으로 연결함
    
Method
addRequestProperty(String a, String b) : 키(a) 와 값(b)을 가지고 요청할 수 있는 
                               Properity 값을 미리 설정해 놓음. 특정 키값을 가지고 읽을 수 있도록 함
connect() : 연결 된 곳에 접속 할때 (connect() 호출해야 실제 통신 가능함)
getAllowUserInteraction() : 연결 된 곳에 사용자가 서버와 통신 할 수 있는 환경 확인(boolean)
                               in/output이 해당 서버 , 연결 포트로 가능한지 확인함
getContent() : content 값을 리턴 받음 (inputStream 값을 리턴 함)
getContent(Class[]) : 위 내용을 class[] 배열 값을 입력함
getContentEncoding() : 인코딩 타입을 String으로 리턴함
getContentLength() : content 길이 (-1 이면 정상적으로 값이 넘어오지 않았음)
getContentType() : content 가 http로 되어 있는지 타입 (ex: http-type )
getDate() : content의 날짜 (new Date(~~) 으로 변환해 줘야 함 / Long 리턴)
getDefaultAllowUserInteraction(): 기본적으로 User와 통신 가능한 상태인지 (boolean)
getDefaultUserCaches() : cache를 사용할 것 인지 (boolean)
getDoInput() : Server에서 온 데이터를 입력 받을 수 있는 상태인지 (본인 상태-default : true)
getDoOutput() : Server에서 온 데이터를 출력 할수 있는 상태인지
                          (Client 상태 -default : false)
getExpiration() : 유효 기간
getFileNameMap() : File Name Map
getHeaderField(int) : Head Field 값 받아옴 (http Head 값)
getHeaderFiled(String) :
getLastModified() : 마지막 수정 시간 

getInputStream() : InputStrema 값을 뽑아냄
getOutputStream() : OutputStream 값을 뽑아냄

setDoInput(boolean) : Server 통신에서 입력 가능한 상태로 만듬 
setDoOutput(boolean) : Server 통신에서 출력 가능한 상태로 만듬
 - Server와 통신을 하고자 할때는 반드시 위 두 method를 true로 해 놔야 함

URL url = null;
URLConnection uc = null;

try{
       url = new URL("http://www.korea.co.kr");
}catch(MalformedURLException me){}

try{    uc = url.openConnection(); }catch(IOException io){}

  System.out.println("output = "+ uc.getDoOutput());
  System.out.println("Input = "+ uc.getDoInput());
  uc.setDoOutput(true);  // 스트림 출력 설정
  uc.setDoInput(true);    // 스트림 입력 설정 -- 기본적으로 입력 스트림
  OutputStream out =null;
  InputStream in = null;
try{
       in = uc.getInputStream();
//   out = uc.getOutputStream();
}catch(IOException ie){}
System.out.println("input = "+ in.toString());
//  System.out.println("out = "+ out.toString());


[예제]
URLConnection을 이용한 Web 페이지 읽어서 저장하기

 

[WebSpiderWithURLConnection.java]

import java.io.FileOutputStream;

import java.io.InputStream;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.text.SimpleDateFormat;

import java.util.Date;

public class WebSpiderWithURLConnection {

    public static void main(String[] args) {

        if (args.length != 2) {

            System.out.println("사용법 : java WebSpider URL filename");

            System.exit(1);

        }

        URL url = null;

        try {

            url = new URL(args[0]);

        } catch (MalformedURLException e1) {

            System.out.println("잘못된 URL 형식입니다.");

            System.out.println(e1);

            System.exit(1);

        }

        FileOutputStream fos = null;

        try {

            URLConnection urlcon = url.openConnection();

            String contentType = urlcon.getContentType();

            long d1 = urlcon.getDate();

            Date d = new Date(d1);

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");

            String sdata = format.format(d);

            System.out.println("Content Type :" + contentType);

            System.out.println("읽어온 시간 : " + sdata);

            InputStream in = urlcon.getInputStream();

            fos = new FileOutputStream(args[1]);

            byte[] buffer = new byte[512];

            int readcount = 0;

            System.out.println("읽어 오기 시작 ");

            while ((readcount = in .read(buffer)) != -1) {

                fos.write(buffer, 0, readcount);

            }

            System.out.println(args[1] + "파일에 모두 저장했습니다.");

        } catch (Exception ex) {

            System.out.println(ex);

        } finally {

            try {

                if (fos != null) fos.close();

            } catch (Exception e) {

            }

        }

    }

}


Get 방식으로 데이터 전달함 (검색 조회해서 결과 저장함)

[GetSearch.java]

import java.io.BufferedReader;

import java.io.FileWriter;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLConnection;

import java.net.URLEncoder;

public class GetSearch {

    public static void main(String[] args) {

        if (args.length != 2) {

            System.err.println("사용법 : java  GetSearch  keyword  filename");

            System.exit(1);

        }

        try {

            String keyword = URLEncoder.encode(args[0]);

            String query = "query=" + keyword + "&frm=t1&sm=top_hty";

            String u = "http://search.naver.com/search.naver";

            System.out.println(u + query);

            URL url = new URL(u);

            URLConnection connection = url.openConnection();

            HttpURLConnection hurlc = (HttpURLConnection) connection;

            hurlc.setRequestMethod("GET");

            hurlc.setDoOutput(true); // 쓰는 기능 on

            hurlc.setDoInput(true); // 읽어 들임 기능 on

            hurlc.setUseCaches(false);

            hurlc.setDefaultUseCaches(false);

            PrintWriter out = new PrintWriter(hurlc.getOutputStream()); // 

            out.println(query);

            out.close();

            BufferedReader in = new BufferedReader(

                new InputStreamReader(hurlc.getInputStream()));

            PrintWriter pw = new PrintWriter(new FileWriter(args[1]));

            String inputLine = null;

            while ((inputLine = in .readLine()) != null) {

                pw.println(inputLine);

            }

            in .close();

            pw.close();

            System.out.println("검색 결과가 " + args[1] + "파일에 저장되었습니다.");

        } catch (Exception ex) {

            System.out.println(ex);

        }

    }

}

 

Post 방식으로 데이터 전달함

[PostConnection.java]

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLConnection;

import java.net.URLEncoder;

public class PostConnection {

    public static void main(String[] args) {

        if (args.length != 2) {

            System.out.println("사용법 : java Postconnection id password");

            System.exit(1);

        }

        try {

            String id = URLEncoder.encode(args[0]);

            String passwd = URLEncoder.encode(args[1]);

            String query = "id=" + id + "&passwd=" + passwd;

            String u = "http://localhost/test.jsp";

            System.out.println(u + query);

            URL url = new URL(u);

            URLConnection connection = url.openConnection();

            HttpURLConnection hurlc = (HttpURLConnection) connection;

            hurlc.setRequestMethod("POST");

            hurlc.setDoOutput(true);

            hurlc.setDoInput(true);

            hurlc.setUseCaches(false);

            hurlc.setDefaultUseCaches(false);

            PrintWriter out = new PrintWriter(hurlc.getOutputStream());

            out.println(query);

            out.close();

            BufferedReader in = new BufferedReader(

                new InputStreamReader(hurlc.getInputStream()));

            String inputLine = null;

            while ((inputLine = in .readLine()) != null) {

                System.out.println(inputLine);

            }

            in .close();

        } catch (Exception ex) {

            System.out.println(ex);

        }

    }

}

 



java.net.URLEncoder - Static method : encode(String, String)
    - Encoding : 아스키 문자가 아닌 문자열들을 특수한 문자들로 변환하는 것 

String  encodeStr = URLEncoder.encode(str,"EUC_KR");

    - 문자셋 : EUC_KR 등 뒤에 붙여줌
    
java.net.URLDecoder - Static method : decode(String, String)

String  decodeStr  = URLDecoder.decode(str,"EUC_KR");



static Method 하나만 존재함
- 네트워크는 데이터를  byte로 전송함, 이를 만드는 것을 Encoder , 
  해제하는 것을 Decoder라고 함

  String data = "테스트 전송";
  String dataconver = null;
  //============ Encoder ==============//
  try{
         dataconver = URLEncoder.encode(data,"KSC5601"); // KSC5601 --> euc-kr
  }catch(UnsupportedEncodingException ie){}
        System.out.println("data = "+ data);
        System.out.println("data conver = "+ dataconver);
  
  // ============ Decoder ============== //
  try{
      dataconver = URLDecoder.decode(dataconver,"KSC5601");
  }catch(UnsupportedEncodingException ue){}
        System.out.println("data conver = "+ dataconver);

결과
data = 테스트 전송
data conver = %C5%D7%BD%BA%C6%AE+%C0%FC%BC%DB
data conver = 테스트 전송


출처 : http://zeroit.tistory.com/214

 

 

=================================

=================================

=================================

 

 

 

반응형

 

 

728x90

 

 

 

 

출처 : http://javacan.tistory.com/entry/35

 

URL과 URLConnection을 이용한 데이터 전송

오늘날 B2B가 IT 업계의 대세로 자리 잡으면서 B2B 기업간에 정보를 주고 받아야 하는 상황이 종종 발생하고 있다. 각 기업간에 정보를 주고 받는 방법에는 데이터베이스를 공유하는 방법, RPC나 RMI 또는 코바를 사용하는 방법 또는 직접 프로토콜을 제작하여 TCP 기반의 통신을 하는 방법 등 다양한 형태가 존재한다.

하지만 이러한 방법들보다 더욱 간단하게 정보를 주고 받을 수 있는 방법이 있다. 바로 웹을 기반으로 해서 정보를 주고 받는 것이다. 웹 프로그래밍은 RMI/RPC/코바 프로그래밍에 비해서 간단하며 보안의 경우도 HTTPS 프로토콜을 사용하여 비교적 간단하게 해결할 수 있다. 더군다나 자바의 경우는 java.net.URLConnection 클래스를 통해서 소켓 프로그래밍을 직접 할 필요 없이 매우 간단하게 웹 페이지를 호출할 수 있도록 하고 있다.

이 글에서는 먼저 URL 클래스와 URLConnection 클래스를 사용하여 웹 기반의 통신을 하는 방법에 대해서 살펴보고, 그 다음으로 웹 기반의 통신 기능을 캡슐화한 HttpMessage 클래스를 작성해볼 것이다.

java.net.URL과 java.net.URLConnection 클래스

앞에서도 언급했듯이 자바는 이미 URLConnection 클래스를 통해서 매우 간단하게 HTTP 프로토콜 기반의 소켓 통신을 할 수 있도록 하고 있다. URLConnection 클래스는 실제로 추상클래스로서 URLConnection 타입을 갖는 인스턴스는 java.net.URL 클래스의 openConnection() 메소드를 통해서 구할 수 있다.

java.net.URL 클래스는 URL을 나타낼 때 사용되며, 프로토콜, 포트 번호, 호스트 이름, 자원의 경로 등의 정보를 포함하고 있다. 예를 들어, 자바캔 웹 사이트를 나타내는 URL 인스턴스를 생성하고자 할 경우 다음과 같이 하면 된다.

  URL url = new URL("http", "www.javacan.com", 80, "index.html");
  URL url = new URL("http://www.javacan.com/index.html");


위의 두 줄은 모두 http://www.javacan.com/index.html 을 URL 클래스를 사용하여 표현한 것이다. java.net.URL 클래스는 FTP, HTTP 프로토콜을 포함하여 대부분의 URL을 표현할 수 있도록 해 주고 있다. 이 글에서는 HTTP 프로토콜에 대한 내용만 언급할 것이므로, java.net.URL 클래스에 대해서 보다 자세한 내용을 알고 싶다면 JDK API 문서나 자바 관련 서적을 참고하기 바란다.

위 코드와 같이 URL 클래스의 인스턴스를 생성하게 되면 openConnection() 메소드를 사용하여 해당하는 URL에 대해 연결된 클래스인 URLConnection 을 얻을 수 있게 된다. 예를 들면 다음과 같다.

  URL url = new URL("http", "www.javacan.com", 80, "index.html");
  URLConnection conn = url.openConnection();


URL 클래스의 openConnection()을 호출하게 되면, URL 클래스가 사용하는 프로토콜에 따라 URLConnection을 상속한 알맞은 하위 클래스의 인스턴스를 얻게 된다. 예를 들어, HTTP 프로토콜을 사용할 경우 openConnection() 메소드는 java.net.HttpURLConnection 클래스의 인스턴스를 리턴하게 된다.

일단 URL 클래스로부터 URLConnection 인스턴스를 구하게 되면 URLConnection.getInputStream() 메소드를 사용하여 원격 자원으로부터 데이터를 읽어올 수 있게 된다. 예를 들어, 다음은 간단하게 파라미터로 입력받은 URL이 나타내는 사이트로부터 데이터를 읽어오는 자바 프로그램이다.

  import java.net.*;
  import java.io.*;
  
  public class ReadDataFromURL {
  
     public static void main(String[] args) throws IOException {
        if (args.length == 0) {
           System.out.println("java ReadDataFromURL URL");
           System.exit(0);
        }
        URL url = new URL(args[0]);
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        char[] buff = new char[512];
        int len = -1;
        
        while( (len = br.read(buff)) != -1) {
           System.out.print(new String(buff, 0, len));
        }
        
        br.close();
     }
  }


위 코드를 보면 특별히 어려운 부분이 느껴지지 않을 것이다. 단순히 URL 클래스의 openConnection() 메소드와 URLConnection 클래스의 getInputStream() 메소드를 차례대로 호출하기만 하면 URL 클래스가 나타내는 자원으로부터 데이터를 읽어올 수 있다. 실제로 다음과 같이 실행함으로써 특정 사이트의 내용을 원하는 파일에 저장할 수도 있다.

  java ReadDataFromURL http://www.javacan.com > javacanindex.html


위 코드에서 조심해야 할 부분이라면 URLConnection.getInputStream() 메소드로부터 얻어진 InputStream으로부터 직접 데이터를 읽어오기 보다는 Reader를 거쳐서 데이터를 읽어온다는 점이다. 이는 InputStream을 사용할 경우 바이트 단위로 데이터를 읽어오기 때문에 한글과 같이 아스키 코드 이외에 글자들이 깨지기 때문이다.

서버에 데이터 전송하기

이제 URL 클래스와 URLConnection 클래스를 사용하여 매우 간단하게 웹 사이트의 내용을 읽어올 수 있다는 것을 알았을 것이다. 하지만, 특정 URL에 있는 데이터를 읽어오는 것만으로는 웹 기반의 데이터 교환을 할 수 없게 된다. 진정으로 웹-투-웹 프로그래밍이 가능하려면 상대방의 웹 사이트에 있는 JSP/PHP/ASP/CGI와 같은 웹 프로그램에 데이터를 전송할 수 있어야 한다.

HTTP 프로토콜은 GET 방식과 POST 방식을 사용하여 데이터를 전송할 수 있도록 하고 있다. 간단히 이 두 방식의 차이점을 설명한다면 GET 방식은 URL을 통해서 서버에 전달되며 POST 방식의 경우는 스트림을 통해서 서버에 전달된다. 전통적인 CGI의 경우 GET 방식의 데이터는 환경 변수를 통해서, POST 방식으로 전달된 데이터는 입력 스트림을 통해서 구할 수 있었으나 자바의 서블릿이나 JSP에서는 이런 하위 레벨은 알 필요 없이 단순히 HttpServletRequest의 getParameter() 메소드를 사용하여 매우 간단하게 클라이언트가 전송한 데이터를 읽어올 수 있다.

이처럼 GET 방식과 POST 방식 사이의 차이점 때문에 서버에 데이터를 전송하는 클래스 역시 이 차이점에 맞춰서 각각의 방식을 알맞게 구현해주어야 한다.

GET 방식으로 데이터 전송하기

먼저 GET 방식으로 데이터를 전송하는 것에 대해서 살펴보자. GET 방식은 앞에서도 언급했듯이 다음과 같이 요청 URL과 함께 전송된다.

  http://somhost.com/jsp/write.jsp?name=...&email=...&....


여기서 물음표 다음에 있는 부분은 서버에 전송될 파라미터의 이름과 데이터를 나타낸다. 각각의 파라미터는 앰퍼샌드 기호(&)를 통해서 분리되며, 각 파라미터의 값은 인코딩된 상태이어야 한다. 파라미터 값의 인코딩은 java.net.URLEncoder 클래스의 static 메소드인 encode() 메소드를 통해서 처리할 수 있다. 예를 들어, 파라미터의 값이 '최범균' 일 경우 이를 인코딩하면 다음과 같은 문장으로 파라미터 값이 변경된다.

  %C3%D6%B9%FC%B1%D5


이처럼 인코딩된 데이터를 GET 방식을 사용하여 파라미터 값으로 전달하고자 할 경우 단순히 URL 뒤에 인코딩된 파라미터 값을 알맞게 추가하기만 하면 된다. 예를 들어, 다음은 간단히 파라미터 값을 인코딩한 형태로 변환해주는 메소드이다.

   public static String encodeString(Properties params) {
      StringBuffer sb = new StringBuffer(256);
      Enumeration names = params.propertyNames();
      
      while (names.hasMoreElements()) {
         String name = (String) names.nextElement();
         String value = params.getProperty(name);
         sb.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value) );
         
         if (names.hasMoreElements()) sb.append("&");
      }
      return sb.toString();
   }


위 코드에 있는 encodeString() 메소드를 보면 java.util.Properties를 파라미터로 전달받는다. java.util.Properties 클래스는 <이름, 값> 쌍을 저장할 수 있는 클래스로서 위 메소드는 파라미터의 이름과 값을 저장하고 있다. 위 코드를 보면 파라미터의 이름과 값 모두 URLEncoder.encode() 메소드를 사용하여 알맞게 인코딩하는 것을 알 수 있다.

encodeString() 메소드를 사용하여 파라미터의 이름과 값을 알맞게 인코딩할 수 있게 되었으므로 이제 GET 방식으로 전송하는 것에 대해 살펴보자. GET 방식으로 파라미터를 전달하기 위해서는 단순히 물음표 뒤에 encodeString() 메소드의 결과값을 연결하기만 하면 된다. 즉, 다음과 같은 형태의 코드를 사용하여 GET 방식의 파라미터를 전송할 수 있다.

   Properties prop = new Properties();
   prop.setProperty(paramName1, paramValue1);
   prop.setProperty(paramName2, paramValue2);
   ...
   String encodedString = encodeString(prop);
   
   URL url = new URL("http://www.host.com/index.jsp" + "?" + encodedString);
   URLConnection conn = url.openConnection();
   conn.setUseCaches(false);
   is = conn.getInputStream();
   ...


앞에서 살펴봤던 ReadDataFromURL 클래스의 main() 메소드와 크게 다르지 않으며, 단지 Properties를 이용하여 인코딩된 문자열을 알맞게 URL에 넣어준 것 밖에 차이점이 없다. 위 코드에서 URLConnection.setUseCaches() 메소드에 파라미터 값을 false를 전달한 것을 알 수 있는데, 이렇게 함으로써 캐시에 저장된 결과가 아닌 동적으로 그 순간에 생성된 결과를 읽어올 수 있게 된다. 이처럼 캐시로부터 값을 읽어오지 않는 이유는 파라미터를 전송하는 경우 대부분 웹 페이지의 결과가 그 순간 순간 파라미터의 값에 따라 달라지기 때문이다.

POST 방식으로 데이터 전송하기

GET 방식으로 파라미터를 전송하는 것은 단순히 URL 뒤에 물음표와 인코딩된 문자열을 연결해주기만 하면 될 정도로 비교적 간단했다. POST 방식의 경우는 스트림을 통해서 파라미터를 전송해야 하기 때문에 URLConnection으로부터 OutputStream을 구해야 한다. 먼저 POST 방식으로 파라미터를 전송해주는 코드부터 살펴보도록 하자.

   URLConnection conn = targetURL.openConnection();
   
   conn.setDoInput(true);
   conn.setDoOutput(true);
   
   conn.setUseCaches(false);
   
   conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
   
   out = null;
   try {
      out = new DataOutputStream(conn.getOutputStream());
      out.writeBytes(encodedParamString);
      out.flush();
   } finally {
      if (out != null) out.close();
   }
   is = conn.getInputStream();
   ...


위 코드를 보면 conn.setDoOutput(ture) 부분을 볼 수 있는데, URLConnection 클래스 setDoOutput() 메소드는 URLConnection의 출력 스트림을 사용할지의 여부를 나타낸다. POST 방식은 스트림 기반의 데이터 전송 방식이기 때문에 setDoOutput(true)를 실행하여 URLConnection의 출력 스트림을 사용하도록 지정해야 한다. 또 setRequestProperty() 메소드를 사용하여 "Content-Type" 프로퍼티를 "application/x-www-form-urlencoded"로 변경해주는 것을 알 수 있는 데, 이렇게 함으로써 웹 서버는 POST 방식의 데이터가 인코딩된 데이터라는 것을 알 수 있게 된다.

URLConnection에 대한 모든 설정이 끝나면 URLConnection.getOutputStream() 메소드를 사용하여 해당 URL에 대한 출력 스트림을 구할 수 있게 되고, 그 출력 스트림에 파라미터를 인코딩한 문자열을 전송하면 된다. 위 코드에서는 DataOutputStream을 사용하여 데이터를 전송하였다.

웹 기반의 통신 기능을 제공하는 HttpMessage 클래스

지금까지 살펴본 내용들은 웹기반 통신을 할 때 필요한 기능들을 부분적으로 설명한 것에 불과하다. 실제로 웹기반 통신을 할 때 마다 앞에서 설명한 코드들을 작성하는 것은 자바의 객체 지향적 특징을 무시(?)하는 처사라 할 수 있다. 이 글에서는 웹 기반의 통신을 쉽게 할 수 있도록 필요한 기능을 캡슐화한 HTTPMessage 클래스를 작성해보도록 하자.

HttpMessage 클래스의 소스 코드

먼저 여러분이 쉽게 접근할 수 있도록 HttpMessage 클래스의 소스 코드부터 살펴보자. HttpMessage 클래스의 소스 코드는 다음과 같다.

  package javacan.http.util;
  
  import java.io.*;
  import java.net.*;
  import java.util.*;
  
  /**
   * HTTP 요청 메시지를 웹서버에 전송한다.
   *
   * @author 최범균, era13@hanmail.net
   */
  public class HttpMessage {
     
     /**
      * HTTP 프로토콜을 사용하여 연결할 URL
      */
     private URL targetURL;
     
     /**
      * POST 방식으로 데이터를 전송할 때 사용되는 출력 스트림
      */
     private DataOutputStream out;
     
     public HttpMessage(URL targetURL) {
        this.targetURL = targetURL;
     }
     
     public InputStream sendGetMessage() throws IOException {
        return sendGetMessage(null);
     }
     
     public InputStream sendGetMessage(Properties params)     throws IOException {
        String paramString = "";
        
        if (params != null) {
           paramString = "?"+encodeString(params);
        }
        URL url = new URL(targetURL.toExternalForm() + paramString);
        
        URLConnection conn = url.openConnection();
        conn.setUseCaches(false);
        return conn.getInputStream();
     }
     
     public InputStream sendPostMessage() throws IOException {
        return sendPostMessage("");
     }
     
     public InputStream sendPostMessage(Properties params)     throws IOException {
        String paramString = "";
        
        if (params != null) {
           paramString = encodeString(params);
        }
        return sendPostMessage(paramString);
     }
  
     private InputStream sendPostMessage(String encodedParamString)     throws IOException {
        URLConnection conn = targetURL.openConnection();
        
        conn.setDoInput(true);
        conn.setDoOutput(true);
        
        conn.setUseCaches(false);
        
        conn.setRequestProperty("Content-Type",
                                   "application/x-www-form-urlencoded")
;
        
        out = null;
        try {
           out = new DataOutputStream(conn.getOutputStream());
           out.writeBytes(encodedParamString);
           out.flush();
        } finally {
           if (out != null) out.close();
        }
        
        return conn.getInputStream();
     }
     
     public static String encodeString(Properties params) {
        StringBuffer sb = new StringBuffer(256);
        Enumeration names = params.propertyNames();
        
        while (names.hasMoreElements()) {
           String name = (String) names.nextElement();
           String value = params.getProperty(name);
           sb.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value) );
           
           if (names.hasMoreElements()) sb.append("&");
        }
        return sb.toString();
     }
  }


HttpMessage 클래스는 생성자로 데이터를 주고 받을 CGI나 JSP 또는 단순한 웹 페이지를 나타내는 URL을 입력받는다. 일단 HttpMessage 객체를 생성하면 sendPostMessage(Properties) 메소드나 sendGetMessage(Properties) 메소드(전송할 파라미터가 없는 경우에는 sendPostMessage() 메소드와 sendGetMessage() 메소드)를 사용하여 지정한 URL로부터 데이터를 읽어올 수 있는 InputStream을 구할 수 있게 된다.

HttpMessage 클래스 사용하기

HttpMessage 클래스는 다음과 같은 순서로 사용하면 된다.

  1. 접속할 URL에 해당하는 java.net.URL 클래스의 인스턴스를 생성한다.
  2. URL 인스턴스를 HttpMessage 클래스의 생성자에 전달하여 HttpMessage 객체를 생성한다.
  3. 전송할 파라미터가 존재할 경우 java.util.Properties 클래스를 사용하여 파라미터의 이름/값 쌍을 저장한다.
  4. sendGetMessage() 메소드나 sendPostMessage() 메소드를 사용하여 원하는 사이트에 데이터를 전송한다.
  5. 단계 4에서 구해진 InputStream으로부터 데이터를 읽어온다.

예를 들어, 다음은 검색엔진 엠파스로부터 특정 단어에 대한 검색 결과를 읽어오는 SearchFromEmpas 클래스를 HttpMessage 클래스를 사용하여 작성한 것이다.

  import java.net.*;
  import java.io.*;
  import javacan.http.util.HttpMessage;
  import java.util.Properties;
  
  public class SearchFromEmpas {
  
     public static void main(String[] args) throws IOException {
        if (args.length == 0) {
           System.out.println("java SearchFromEmpas 검색어");
           System.exit(0);
        }
        
        URL url = new URL("http://search.empas.com/search/all.html");
        HttpMessage httpMessage = new HttpMessage(url);        
        Properties prop = new Properties();
        prop.setProperty("q", args[0]);
        prop.setProperty("m", "X");
        prop.setProperty("s", "s");
        prop.setProperty("e", "1");
        prop.setProperty("n", "10");
        
        InputStream is = httpMessage.sendGetMessage(prop);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        char[] buff = new char[512];
        int len = -1;
        
        while( (len = br.read(buff)) != -1) {
           System.out.print(new String(buff, 0, len));
        }
        br.close();
     }
  }


다음과 같이 실행하면 SearchFromEmpas 클래스를 사용하여 엠파스로부터 검색 결과가 출력될 것이다. 만약 검색 결과를 파일로 저장하고 싶다면 명령어 뒤에 리디렉션( '>' )을 사용하면 된다.

  java SearchFromEmpas 자바캔


실제로 메타 검색 엔진의 구현은 SearchFromEmpas 클래스와 비슷한 형태로부터 시작된다.

HttpMessage 클래스를 사용할 때의 주의점

한국에 있는 자바 개발자들이 자바를 사용하여 어플리케이션을 개발하면서 겪게 되는 고통중의 하나를 꼽으라면 바로 한글 문제이다. 하지만 한글 문제는 자바에서 사용하는 유니코드와 각 규약에 정의되어 있는 내용을 이해하지 못한 되서 비롯되는 경우가 많으며 올바르게 캐릭터셋에 대한 내용을 이해하고 있다면 매우 간단하게 해결할 수 있는 부분이다.

HttpMessage 클래스 역시 아무 생각없이 사용한다면 한글 문제를 발생시키는 범인이 될 수도 있다. HttpMessage 클래스는 자바 어플리케이션에서 사용될 수도 있겠지만 웹 기반의 통신의 경우에는 서블릿이나 JSP 내에서 사용될 수도 있을 것이다. 이 경우 HttpMessage 클래스에 전달되는 Properties의 값들은 JSP나 서블릿의 HttpServletRequest 객체로부터 읽어온 파라미터가 될 수도 있다.

예를 들어, 다음과 같이 JSP 페이지에서 HttpMessage 클래스를 사용한다고 해 보자.

  <%@ page import = "javacan.http.util.HttpMessage" %>
  <%@ page import = "java.io.*" %>
  <%
     URL url = new URL("http://some.host.com");
     HttpMessage httpMessage = new HttpMessage(url);
     Propertie param = new Properties();
     param.setProperty("name", request.getParameter("name"));
     param.setProperty("address", request.getParameter("address"));
     
     InputStream is = httpMessage.sendGetMessage(param);
     // is 으로부터 값을 읽어와 알맞은 처리를 한다.
     ...
  %>
  ...


별다른 문제가 없어 보이지만, 서블릿/JSP 규약에 따라 사용자의 요청 데이터는 자동적으로 iso-8859-1 캐릭터 셋으로 읽허진다. 즉, request.getParameter() 메소드의 결과값은 iso-8859-1 캐릭터 셋으로 되어 있으며, 따라서 httpMessage 클래스의 sendGetMessage() 메소드는 euc-kr이 아닌 iso-8859-1을 전송하게 되며 따라서 HttpMessage가 연결하는 URL은 깨진 글자를 파라미터로 전달받게 된다.

서블릿에서도 이와 같은 문제가 발생한다. 이 문제의 해결방법은 의외로 간단한다. JSP나 서블릿에서 오라클을 사용할 때와 비슷하게 request.getParameter() 메소드를 사용하여 읽어온 값의 캐릭터 셋을 변환해주는 것이다. 이때 변환은 iso-8859-1 캐릭터 셋에서 euc-kr 로 일어난다. 반대로 HttpMessage 로부터 읽어온 값을 JSP 페이지나 서블릿을 통해서 웹브라우저에 출력할 때에도 캐릭터 셋과 관련된 문제가 발생할 것이다. 이 경우에는 앞에서 살펴본 것과 반대로 캐릭터 셋을 변환해주면 될 것이다.

결론

Part 1에서는 웹기반의 통신(웹-투-웹 통신) 기능을 제공하는 HttpMessage 클래스를 작성해보았다. 이 클래스를 통해서 우리는 GET 방식과 POST 방식을 사용하여 웹 서버에 데이터를 전송할 수 있게 되었으며, 또한 서버로부터 데이터를 전송받을 수 있게 되었다. 다음 Part 2에서는 실제로 웹-투-웹 프로그래밍을 응용하여 XML 기반의 데이터를 전송받는 것에 대해서 알아보도록 하자.

[출처] 안드로이드 - URL과 URLConnection을 이용한 데이터 전송|작성자 실바

 

 

=================================

=================================

=================================

 

 

 

출처: http://androi.tistory.com/65

 

android HttpClient 예제 get, post 방식

 

get방식

HttpClient client = new DefaultHttpClient();
String url = "http://localhost:8080";
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
 Log.w("reponse", EntityUtils.toString(resEntity));      
}

 

위 소스에서 try~ catch를 적용하면

HttpClient client = new DefaultHttpClient();
String url = "http://localhost:8080";
HttpGet get = new HttpGet(url);
HttpResponse response = null;
  try {
      response = client.execute(get);
  } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }
HttpEntity resEntity = response.getEntity();
String sRes = "";
if(resEntity != null){
     try {
     sRes = EntityUtils.toString(resEntity); 
     //sRes = URLDecoder.decode(sRes);
     Log.w("SNSApp", "response: " + sRes); 
     Toast.makeText(mContext, sRes, Toast.LENGTH_SHORT).show();
      } catch (ParseException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }      
}

 

     

post방식

HttpClient client = new DefaultHttpClient();
String postUrl = "http://222.jsp";
HttpPost post = new HttpPost(postUrl);
List params  = new ArrayList();
params.add(new BasicNameVal!uePair("deliveryDate", "1111111111"));


UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePost = client.execute(post);
HttpEntity resEntity = responsePost.getEntity();
if(resEntity != null){
 Log.w("Response", EntityUtils.toString(resEntity));
}

 

출처 : http://cafe.naver.com/infinityjava/206

 

 

=================================

=================================

=================================

 

 

출처: http://unikys.tistory.com/197

1) 안드로이드 앱으로 인터넷 접속을 허용한다.

- 아래 태그를 

<uses-permission android:name="android:name="android.permission.INTERNET" />


2) Get을 하는 방법

public InputStream getInputStreamFromUrl(String url) {
  InputStream content = null; 

  try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(url));
    content = response.getEntity().getContent();
  } catch (Exception e) {
    Log.("[GET REQUEST]", "Network exception", e);
  }
  return content;
}


3) Post를 하는 방법

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }


4) 위의 소스코드는 AsyncTask에서 실행한다.
* main thread에서 실행하면 android.os.NetworkOnMainThreadException

class HttpTask extends AsyncTask<String , Void , String> {
  protected String doInBackground(String... params)
  {
    InputStream is = getInputStreamFromUrl(params[0]);

    String result = convertInputStreamToString(is);//이 함수는 이 페이지를 참고

    return result;
  }

  protected void onPostExecute(String result)
  {
    //result를 처리한다.
  }


- 위의 클래스를 실행하는 방법은

new HttpTask().execute("http://접근하고자하는URL"); 


- AsyncTask의 템플릿은 입맛에 따라 바꿔서 사용하면 된다.

끝.

 

 

 

=================================

=================================

=================================

 

 

출처: http://arabiannight.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9CAndroid-HttpURLConnection-%EC%97%90%EC%84%9C-GET-POST-%EB%B0%A9%EC%8B%9D-%EC%82%AC%EC%9A%A9%EC%83%81%EC%9D%98-%EC%A3%BC%EC%9D%98

 

안드로이드/Android HttpURLConnection 에서 GET / POST 방식 사용상의 주의

 

 

1. HttpURLConnection 을 이용하여 GET 혹은 POST 방식으로 특정 서블릿을 호출하는 경우

HttpURLConnection.setRequestMethod("GET") 이라고 명시적으로 GET 을 지정하여도,

특정한 경우에는 내부적으로 POST로 처리함을 주의해야 한다.

 

HttpURLConnection.getOutputStream() 메소드 내부에서 현재 지정된 method 가 GET 인 경우

강제로 POST 로 변경한다.

 

따라서, 

con.setRequestMethod("GET");  로 GET 으로 설정했다고 하더라도,

아래의 라인이 추가된다면, 

con.setDoOutput(true);

OutputStream out = con.getOutputStream();

내부적으로 POST 방식으로 변경된다.

 

2. 실질적으로 웹서버에 접속하여 요청을 보내고 응답을 수신하는 시점은

con.getResponseCode(); 로 판단된다.

getResponseCode() 를 호출하지 않으면, Network Connection 연결 요청 자체가 시도되지 않음이

확인되었다.. 다른 구현에서는 어떠한지 확인할 필요가 있다.

 

========================== sample code =================================

 

 
 URL url_obj = new URL("http://테스트서블릿URL"); HttpURLConnection con = (HttpURLConnection)url_obj.openConnection();
 con.setRequestMethod("GET");              // default is GET
 con.setDoInput(true);                            // default is true
 con.setDoOutput(true);                          //default is false
 InputStream in = con.getInputStream();
 OutputStream out = con.getOutputStream();  // internally change to 'POST'
 int resCode = con.getResponseCode();  // connect, send http reuqest, receive htttp request
 System.out.println ("code = "+ resCode); 

 

 

========================= 서버 access.log ================================

 


 203.242.137.163 - - [25/Jan/2008:16:08:04 +0900] "POST /테스트서블릿 HTTP/1.0" 200 1639
  

 

 

=================================

=================================

=================================

 

 

 

출처 : http://charmpa.egloos.com/1336665

 

 

안드로이드/Android HttpURLConnection Request Header 값 세팅 하기

 

 

안드로이드 서버 통신 사용시 Request Header 에 값을 전달해서 보내는 방법 입니다.

?

URL url = new URL("URL"); 
HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
conn.setRequestProperty("User-Agent", "test");         
conn.setRequestProperty("Value1", "test");
conn.setRequestProperty("Value2", "test");
conn.setRequestProperty("Value3", "test");
conn.setRequestProperty("Value4", "test");
conn.setRequestProperty("Value5", "test");

 

setRequestProperty 메서드에 해당 Data값을 (Key, value) 형태로 추가해 주시면 됩니다.

 

 

=================================

=================================

=================================

 

 

 

출처:http://arabiannight.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9CAndroid-HttpURLConnection%ED%81%B4%EB%9E%98%EC%8A%A4%EB%A1%9C-POST-%EC%9A%94%EC%B2%AD%ED%95%98%EA%B8%B0

 

안드로이드/Android HttpURLConnection클래스로 POST 요청하기

 

 

// 요청할 파라미터의 정보를 입력한다.

String body = "id=asdf&pass=asdf";

// URL클래스의 생성자로 주소를 넘겨준다.

URL u = new URL( 주소 ); 

// 해당 주소의 페이지로 접속을 하고, 단일 HTTP 접속을 하기위해 캐스트한다.

HttpURLConnection  huc = (HttpURLConnection) u.openConnection();

// POST방식으로 요청한다.( 기본값은 GET )

huc.setRequestMethod("POST");

// InputStream으로 서버로 부터 응답 헤더와 메시지를 읽어들이겠다는 옵션을 정의한다.

huc.setDoInput(true);

// OutputStream으로 POST 데이터를 넘겨주겠다는 옵션을 정의한다.

huc.setDoOutput(true);

// 요청 헤더를 정의한다.( 원래 Content-Length값을 넘겨주어야하는데 넘겨주지 않아도 되는것이 이상하다. )

huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// 새로운 OutputStream에 요청할 OutputStream을 넣는다.

OutputStream os = huc.getOutputStream();

// 그리고 write메소드로 메시지로 작성된 파라미터정보를 바이트단위로 "EUC-KR"로 인코딩해서 요청한다.

// 여기서 중요한 점은 "UTF-8"로 해도 되는데 한글일 경우는 "EUC-KR"로 인코딩해야만 한글이 제대로 전달된다.

os.write( body.getBytes("euc-kr") );

// 그리고 스트림의 버퍼를 비워준다.

os.flush();

// 스트림을 닫는다.

os.close();

// 응답받은 메시지의 길이만큼 버퍼를 생성하여 읽어들이고, "EUC-KR"로 디코딩해서 읽어들인다.

BufferedReader br = new BufferedReader( new OutputStreamReader( huc.getInputStream(), "EUC-KR" ), huc.getContentLength() );

String buf;

// 표준출력으로 한 라인씩 출력

while( ( buf = br.readLine() ) != null ) {

System.out.println( buf );

}

// 스트림을 닫는다.

br.close();

 

 

출처 : http://ibabo.tistory.com/266

 

 

참고 사이트 : 

클래스 java.net.URLConnection 한글 API

클래스 java.net.HttpURLConnection 한글 API

클래스 java.io.InputStream 한글 API

클래스 java.io.OutputStream 한글 API

 

 

=================================

=================================

=================================

 

 

 

안드로이드/Android String.getBytes() 사용법

 

 

사용하는 플렛폼이나 사용하는 개발언어에 따라 기본적으로 셋팅되어 있는 한글 코드값이 다를 경우가 있다. 이때 코드값을 적절하게 변형하여 사용해야 하는데 String클래스의 getBytes()메소드를 사용하면 편할 것이다.

 

String str="박원기";

String s=new String(str.getBytes("8859_1"),"KSC5601");

 

위 의 코드는 "박원기"란 문자를 8859_1 코드셋으로 받아들여 KSC5601로 변환하여 새로운 스트링 s를 만들게 된다. 위의 코드를 활용하여 애플리케이션에서 DB로, DB에서 애플리케이션으로 한글을 처리할 때 사용할 수 있는 메소드를 만들어 보자.

 

데이터 베이스 사용코드 : 8859_1

응용 애플리케이션 사용코드 : KSC5601 일 경우

// 한글 데이터를 데이터 베이스로부터 가져올때
public String fromDB(String str) throws Exception
{
    String s=new String(str.getBytes("8859_1"),"KSC5601");
    return s;
}


// 한글 데이터를 데이터 베이스에 저장할때
public String toDB(String str) throws Exception
{
    String s=new String(str.getBytes("KSC5601"),"8859_1");
    return s;
}

 

출처 : http://glory.tistory.com/

 

 

=================================

=================================

=================================

 

 

반응형


관련글 더보기

댓글 영역