Android如何将GET和JSON数据发送到服务器并获得响应

时间:2014-08-13 08:32:11

标签: android json get

您好我需要发送到服务器。并从服务器获得响应。 数据是JSON。我需要像在WEB中一样将数据添加到URL吗? 我一直有错误需要帮助

    HttpClient httpClient = new DefaultHttpClient();  
        String url = "http://api.avakoo.com/Entry.svc/JSON/Register?args=%7B%22password%22%3A%22vhfju%22%2C%22email%22%3A%22fhcnh%22%7D";
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            entity.writeTo(out);
            out.close();
            String responseStr = out.toString();

我说一些例子但是民族工作可以有人告诉我如何发送日期并从服务器获得响应。 当我但浏览器中的URL我得到了回复。 我将数据编码为白色utf 8

2 个答案:

答案 0 :(得分:0)

你可以试试这个。

  DefaultHttpClient httpClient = new DefaultHttpClient();
  String url = "http://api.avakoo.com/Entry.svc/JSON/Register";
  List<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("column name", password));
  params.add(new BasicNameValuePair("column name", email));
  params.add(new BasicNameValuePair("column name",fhcnh ));
  String paramString = URLEncodedUtils.format(params, "utf-8");
  url += "?" + paramString;
  HttpGet httpGet = new HttpGet(url);

  HttpResponse httpResponse = httpClient.execute(httpGet);
  HttpEntity httpEntity = httpResponse.getEntity();
  static InputStream is  = httpEntity.getContent();

希望它会有所帮助..

答案 1 :(得分:0)

以下是您的要求的示例代码

Downlooad Gson jar文件

  String url = "Your url";

  grabURL(url);

        private void grabURL(String url) {


            new GrabURL().execute(url);


        }

  private void displayData(String response){


            String resp = response;

                JSONObject responseObj = null;

                try {
                    Gson gson = new Gson();
                    responseObj = new JSONObject(response); 
                    JSONArray passDataListObj = responseObj.getJSONArray("your array list name from server");

                    ArrayList<ObjectTypeSpecifiedInServer>list = new ArrayList<ObjectTypeSpecifiedInServer>(); 
                    String[] passData_array = new String[passDataListObj.length()]; 

                    for (int i=0; i<passDataListObj.length(); i++){

                        //add to values to array
                        passData_array[i] = passDataListObj.getJSONObject(i).getString("KeyNameGivenForTheValue");

                        //get the value information JSON object
                        String passInfo = passDataListObj.getJSONObject(i).toString();
                        //create java object from the JSON object
                        ObjectType objectReference = gson.fromJson(objectReference , ObjectType.class);
                        }

                }catch (JSONException e) {
                    e.printStackTrace();
                    }

            }
        }



       class GrabURL extends AsyncTask<String, Void, String> {
                private static final int REGISTRATION_TIMEOUT = 3 * 1000;
                private static final int WAIT_TIMEOUT = 30 * 1000;
                private final HttpClient httpclient = new DefaultHttpClient();
                final HttpParams params = httpclient.getParams();
                HttpResponse response;
                private String content =  null;
                private boolean error = false;
                private ProgressDialog dialog = new ProgressDialog(ClassName.this);

                protected void onPreExecute() {

                    dialog.setMessage("Getting your data... Please wait...");
                    dialog.show();

                }

                protected String doInBackground(String... urls) {


                    String URL = null;

                    try {
                        URL = urls[0];
                        HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
                         HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
                         ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
                         HttpPost httpPost = new HttpPost(URL);
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                        nameValuePairs.add(new BasicNameValuePair("uname", username.getText().toString()));
                        nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));

                        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

                        response = httpclient.execute(httpPost);

                        StatusLine statusLine = response.getStatusLine();

                        if(statusLine.getStatusCode() == HttpStatus.SC_OK){

                            ByteArrayOutputStream out = new ByteArrayOutputStream();

                            response.getEntity().writeTo(out);

                            out.close();

                            content = out.toString();

                        } else{
                            //Closes the connection.

                            response.getEntity().getContent().close();
                            throw new IOException(statusLine.getReasonPhrase());
                        }
                    } catch (ClientProtocolException e) {
                        Log.w("HTTP2:",e );
                        content = e.getMessage();
                        error = true;
                        cancel(true);
                    } catch (IOException e) {
                        Log.w("HTTP3:",e );
                        content = e.getMessage();
                        error = true;
                        cancel(true);
                    }catch (Exception e) {
                        Log.w("HTTP4:",e );
                        content = e.getMessage();
                        error = true;
                        cancel(true);
                    }

                    return content;
                }

                protected void onCancelled() {
                    dialog.dismiss();
                    Toast toast = Toast.makeText(ClassName.this, "Error connecting to Server", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.TOP, 25, 400);
                    toast.show();

                }

                protected void onPostExecute(String content) {
                    dialog.dismiss();
                    Toast toast;
                    if (error) {
                        toast = Toast.makeText(ClassName.this, content, Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.TOP, 25, 400);
                        toast.show();
                    } else {
                        displayData(content);
                    }
                }
            }

希望这可以帮助你......