Android에서 요청을 통해 JSON 개체를 보내는 방법은 무엇입니까?


115

다음 JSON 텍스트를 보내고 싶습니다.

{"Email":"aaa@tbbb.com","Password":"123456"}

웹 서비스에 연결하고 응답을 읽습니다. JSON을 읽는 방법을 알고 있습니다. 문제는 위의 JSON 객체를 변수 이름으로 보내야한다는 것 jason입니다.

Android에서 어떻게 할 수 있습니까? 요청 객체 생성, 콘텐츠 헤더 설정 등과 같은 단계는 무엇입니까?

답변:


97

Android에는 HTTP 송수신을위한 특수 코드가 없으므로 표준 Java 코드를 사용할 수 있습니다. Android와 함께 제공되는 Apache HTTP 클라이언트를 사용하는 것이 좋습니다. 다음은 HTTP POST를 보내는 데 사용한 코드 스 니펫입니다.

"jason"이라는 변수로 개체를 보내는 것이 어떤 것과 관련이 있는지 이해하지 못합니다. 서버가 정확히 무엇을 원하는지 잘 모르겠다면 어떤 형식이 필요한지 알 때까지 다양한 문자열을 서버에 보내는 테스트 프로그램을 작성하는 것이 좋습니다.

int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
    postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);

21
postMessage는 JSON 객체입니까?
— AndroidDev

postMessage정의되지 않았습니다
— Raptor 2014 년

시간 제한은 무엇입니까?
— Lion789 2014 년

둘 이상의 문자열을 전달하면 어떨까요? 같은 postMessage2.toString () getBytes ( "UTF8").
— Mayur R. Amipara

POJO를 Json 문자열로 변환하는 제안?
— tgkprog

155

Apache HTTP Client를 사용하면 Android에서 json 객체를 쉽게 보낼 수 있습니다. 이를 수행하는 방법에 대한 코드 샘플은 다음과 같습니다. UI 스레드를 잠그지 않도록 네트워크 활동에 대한 새 스레드를 만들어야합니다.

    protected void sendJson(final String email, final String pwd) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                    HttpPost post = new HttpPost(URL);
                    json.put("email", email);
                    json.put("password", pwd);
                    StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */
                    if(response!=null){
                        InputStream in = response.getEntity().getContent(); //Get the data in the entity
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                    createDialog("Error", "Cannot Estabilish Connection");
                }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();      
    }

Google Gson 을 사용 하여 JSON을 보내고 검색 할 수도 있습니다 .


안녕하세요 서버에서 헤더 caled JSON을 설정하고 해당 헤더에 json 콘텐츠를 넣어야 할 수 있습니까? URL을 HttpPost post = new HttpPost ( " abc.com/xyz/usersgetuserdetails" ); 그러나 그 말하는 잘못된 요청 오류입니다. 코드의 반향은 동일합니다. 둘째로 json = header = new JSONObject (); 무엇이 여기 일어나고
— AndroidDev

서버에서 어떤 종류의 요청을 기대하는지 잘 모르겠습니다. 이 'json = header = new JSONObject (); '2 개의 json 객체를 생성하는 것입니다.
— Primal Pappachan

@primpop-간단한 PHP 스크립트를 제공 할 수있는 기회가 있습니까? 귀하의 코드를 구현하려고 시도했지만 평생 동안 NULL이 아닌 다른 것을 보낼 수 없었습니다.
— kubiej21

다음과 같은 문자열로 inputsputstream (여기 객체에서)의 출력을 얻을 수 있습니다. StringWriter writer = new StringWriter (); IOUtils.copy (in, writer, "UTF-8"); 문자열 theString = writer.toString ();
— Yekmer Simsek

35
public void postData(String url,JSONObject obj) {
    // Create a new HttpClient and Post Header

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient(myParams );
    String json=obj.toString();

    try {

        HttpPost httppost = new HttpPost(url.toString());
        httppost.setHeader("Content-type", "application/json");

        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se); 

        HttpResponse response = httpclient.execute(httppost);
        String temp = EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);


    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
}

ASP.Net mvc 서버에 json 개체를 게시했습니다. ASP.Net 서버에서 동일한 json 문자열을 어떻게 쿼리 할 수 ​​있습니까?
— Karthick

19

HttpPostAndroid Api 레벨 22에서 더 이상 사용되지 않습니다 HttpUrlConnection.

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

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

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

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

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

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

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

1
허용되는 답변은 감가 상각
— 이며이

8

아래 링크에는 놀랍도록 멋진 Android HTTP 용 라이브러리가 있습니다.

http://loopj.com/android-async-http/

간단한 요청은 매우 쉽습니다.

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});

JSON을 보내려면 ( https://github.com/loopj/android-async-http/issues/125 에서`voidberg '에 대한 크레딧 ) :

// params is a JSONObject
StringEntity se = null;
try {
    se = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
    // handle exceptions properly!
}
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

client.post(null, "www.example.com/objects", se, "application/json", responseHandler);

모두 비동기식이며 Android에서 잘 작동하며 UI 스레드에서 안전하게 호출 할 수 있습니다. responseHandler는 생성 한 동일한 스레드 (일반적으로 UI 스레드)에서 실행됩니다. JSON에 대한 내장 resonseHandler도 있지만 Google gson을 사용하는 것을 선호합니다.


이것이 실행되는 최소 SDK를 알고 있습니까?
— Esko918

GUI가 아니기 때문에 최소값이 있다면 놀랄 것입니다. 시도해보고 결과를 게시 해보십시오.
— Alex

1
대신 네이티브 라이브러리를 사용하기로 결정했습니다. 그것에 대해 더 많은 정보가 있으며 안드로이드에 상당히 익숙한 이후입니다. Im 정말 iOS 개발자입니다. 다른 사람의 코드를 연결하고 재생하는 대신 모든 문서를 읽으므로 더 좋습니다. 감사합니다
— Esko918

3

이제는 HttpClient더 이상 사용되지 않으므로 현재 작업 코드는를 HttpUrlConnection사용하여 연결을 만들고 연결에서 읽고 쓰는 것입니다. 하지만 저는 Volley를 선호했습니다 . 이 라이브러리는 Android AOSP에서 가져온 것입니다. 내가하기 위해 사용하는 매우 쉽게 발견 JsonObjectRequest또는JsonArrayRequest


2

이것보다 간단 할 수는 없습니다. OkHttpLibrary 사용

JSON 만들기

JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);

이렇게 보내주세요.

OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .url(url)
            .post(requestObject.toString())
            .build();

okhttp3.Response response = client.newCall(request).execute();

유용한 라이브러리 인 okhttp를 가리 키도록 찬성했지만 주어진 코드는별로 도움이되지 않습니다. 예를 들어, RequestBody.create ()에 전달 된 인수는 무엇입니까? 자세한 내용은이 링크를 참조 vogella.com/tutorials/JavaLibrary-OkHttp/article.html
— 물장난

0
public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
    JSONArray array;
    @Override
    protected JSONArray doInBackground(Void... params) {

        try {
            commonurl cu = new commonurl();
            String u = cu.geturl("tempshowusermain.php");
            URL url =new URL(u);
          //  URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("lid",lid);


            DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            outputStream.write(jsonObject.toString().getBytes("UTF-8"));

            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                StringBuffer stringBuffer = new StringBuffer();
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                object =  new JSONObject(stringBuffer.toString());
             //   array = new JSONArray(stringBuffer.toString());
                array = object.getJSONArray("response");

            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return array;


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();



    }

    @Override
    protected void onPostExecute(JSONArray array) {
        super.onPostExecute(array);
        try {
            for (int x = 0; x < array.length(); x++) {

                object = array.getJSONObject(x);
                ComonUserView commUserView=new ComonUserView();//  commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
                //pidArray.add(jsonObject2.getString("pid").toString());

                commUserView.setLid(object.get("lid").toString());
                commUserView.setUname(object.get("uname").toString());
                commUserView.setAboutme(object.get("aboutme").toString());
                commUserView.setHeight(object.get("height").toString());
                commUserView.setAge(object.get("age").toString());
                commUserView.setWeight(object.get("weight").toString());
                commUserView.setBodytype(object.get("bodytype").toString());
                commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
                commUserView.setImagepath(object.get("imagepath").toString());
                commUserView.setDistance(object.get("distance").toString());
                commUserView.setLookingfor(object.get("lookingfor").toString());
                commUserView.setStatus(object.get("status").toString());

                cm.add(commUserView);
            }
            custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
          gridusername.setAdapter(custuserprof);
            //  listusername.setAdapter(custuserprof);
            } catch (Exception e) {

                e.printStackTrace();
        }
    }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.