Programming

Android에서 HTTPClient를 사용하여 JSON으로 POST 요청을 보내는 방법은 무엇입니까?

procodes 2020. 7. 28. 22:02
반응형

Android에서 HTTPClient를 사용하여 JSON으로 POST 요청을 보내는 방법은 무엇입니까?


HTTPClient를 사용하여 Android에서 JSON을 POST하는 방법을 알아 내려고합니다. 나는 이것을 잠시 동안 알아 내려고 노력했지만 온라인에서 많은 예제를 발견했지만 그중 어떤 것도 작동시킬 수는 없습니다. 나는 이것이 일반적으로 JSON / 네트워킹 지식이 부족하기 때문이라고 생각합니다. 나는 많은 예제가 있지만 누군가 실제 튜토리얼을 지적 할 수 있습니까? 코드를 사용하여 단계별 프로세스를 찾고 있는데 각 단계를 수행하는 이유 또는 해당 단계가 수행하는 작업에 대한 설명입니다. 복잡하고 단순한 의지로 충분할 필요는 없습니다.

다시 말하지만, 거기에 많은 예가 있다는 것을 알고 있습니다. 정확히 무슨 일이 일어나고 있으며 왜 그렇게하고 있는지에 대한 설명이있는 예를 찾고 있습니다.

누군가이 좋은 안드로이드 책에 대해 알고 있다면 알려주십시오.

@terrance 도움말에 다시 한 번 감사드립니다. 아래에 설명 된 코드가 있습니다.

public void shNameVerParams() throws Exception{
     String path = //removed
     HashMap  params = new HashMap();

     params.put(new String("Name"), "Value"); 
     params.put(new String("Name"), "Value");

     try {
        HttpClient.SendHttpPost(path, params);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 }

이 답변에서는 Justin Grammens가 게시 한 예를 사용하고 있습니다.

JSON 정보

JSON은 JavaScript Object Notation의 약어입니다. 자바 스크립트에서는 이와 같이 object1.name또는 이와 같이 속성을 참조 할 수 있습니다 object['name'];. 기사의 예제는이 비트의 JSON을 사용합니다.


전자 메일을 키로 사용하고 foo@bar.com을 값으로 사용하는 부품 A 팬 객체

{
  fan:
    {
      email : 'foo@bar.com'
    }
}

따라서 동등한 객체는 fan.email;또는 fan['email'];입니다. 둘 다 같은 값을가집니다 'foo@bar.com'.

HttpClient 요청 정보

다음은 저자가 HttpClient 요청 을 작성하는 데 사용한 것 입니다. 나는 이것에 대해 전문가라고 주장하지 않으므로 누군가가 용어의 일부를 더 잘 표현할 수 있다면 자유롭게 느끼십시오.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

지도

Map데이터 구조에 익숙하지 않은 경우 Java 맵 참조를 살펴보십시오 . 간단히 말해지도는 사전 또는 해시와 유사합니다.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be 'foo@bar.com' 
    //{ fan: { email : 'foo@bar.com' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and 'foo@bar.com'  together in map
        holder.put(key, data);
    }
    return holder;
}

이 게시물과 관련하여 발생하는 질문이나 명확하지 않은 내용이나 여전히 혼란스러워하는 부분을 만지지 않은 경우 자유롭게 머리에 들리는 내용에 대해 언제든지 의견을 말하십시오.

(저스틴 그라 민스 (Justin Grammens)가 승인하지 않으면 아래로 내려가겠습니다.

최신 정보

방금 코드를 사용하는 방법에 대한 의견을 얻었고 리턴 유형에 실수가 있음을 깨달았습니다. 메소드 서명은 문자열을 리턴하도록 설정되었지만이 경우에는 아무것도 리턴하지 않았습니다. 서명을 HttpResponse로 변경하고 HttpResponse응답 본문 얻기 에있는이 링크를 참조합니다 . 경로 변수는 URL이며 코드의 실수를 수정하기 위해 업데이트되었습니다.


@Terrance의 답변에 대한 대안 솔루션은 다음과 같습니다. 전환을 쉽게 아웃소싱 할 수 있습니다. GSON 라이브러리는 JSON에 다양한 데이터 구조 및 다른 방법의 주위를 변환 멋진 작업을 수행합니다.

public static void execute() {
    Map<String, String> comment = new HashMap<String, String>();
    comment.put("subject", "Using the GSON library");
    comment.put("message", "Using libraries is convenient.");
    String json = new GsonBuilder().create().toJson(comment, Map.class);
    makeRequest("http://192.168.0.1:3000/post/77/comments", json);
}

public static HttpResponse makeRequest(String uri, String json) {
    try {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(new StringEntity(json));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        return new DefaultHttpClient().execute(httpPost);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Similar can be done by using Jackson instead of Gson. I also recommend taking a look at Retrofit which hides a lot of this boilerplate code for you. For more experienced developers I recommend trying out RxAndroid.


I recommend using this HttpURLConnectioninstead HttpGet. As HttpGet is already deprecated in Android API level 22.

HttpURLConnection httpcon;  
String url = null;
String data = null;
String result = null;
try {
  //Connect
  httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
  httpcon.setDoOutput(true);
  httpcon.setRequestProperty("Content-Type", "application/json");
  httpcon.setRequestProperty("Accept", "application/json");
  httpcon.setRequestMethod("POST");
  httpcon.connect();

  //Write       
  OutputStream os = httpcon.getOutputStream();
  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
  writer.write(data);
  writer.close();
  os.close();

  //Read        
  BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));

  String line = null; 
  StringBuilder sb = new StringBuilder();         

  while ((line = br.readLine()) != null) {  
    sb.append(line); 
  }         

  br.close();  
  result = sb.toString();

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

Too much code for this task, checkout this library https://github.com/kodart/Httpzoid Is uses GSON internally and provides API that works with objects. All JSON details are hidden.

Http http = HttpFactory.create(context);
http.get("http://example.com/users")
    .handler(new ResponseHandler<User[]>() {
        @Override
        public void success(User[] users, HttpResponse response) {
        }
    }).execute();

There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.

/**
 * This method is used to process GET requests to the server.
 * 
 * @param url 
 * @return String
 * @throws IOException
 */
public static String connect(String url) throws IOException {

    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    try {

        response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            //instream.close();
        }
    } 
    catch (ClientProtocolException e) {
        Utilities.showDLog("connect","ClientProtocolException:-"+e);
    } catch (IOException e) {
        Utilities.showDLog("connect","IOException:-"+e); 
    }
    return result;
}


 /**
 * This method is used to send POST requests to the server.
 * 
 * @param URL
 * @param paramenter
 * @return result of server response
 */
static public String postHTPPRequest(String URL, String paramenter) {       

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(URL);
    httppost.setHeader("Content-Type", "application/json");
    try {
        if (paramenter != null) {
            StringEntity tmp = null;
            tmp = new StringEntity(paramenter, "UTF-8");
            httppost.setEntity(tmp);
        }
        HttpResponse httpResponse = null;
        httpResponse = httpclient.execute(httppost);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            InputStream input = null;
            input = entity.getContent();
            String res = convertStreamToString(input);
            return res;
        }
    } 
     catch (Exception e) {
        System.out.print(e.toString());
    }
    return null;
}

참고URL : https://stackoverflow.com/questions/6218143/how-to-send-post-request-in-json-using-httpclient-in-android

반응형