如何使用HttpUrlConnection详细信息为android请求params的帖子

时间:2016-03-31 06:26:52

标签: android json

请使用HttpUrlConnection与键,值对参数分享POST Request的{​​strong>完整答案。登录屏幕具有用户名,密码字段,需要发布服务器的值以及获得 json响应,状态为" TRUE "。不想使用Volley Library  请详细回答或分享链接,谢谢你。

4 个答案:

答案 0 :(得分:2)

通过以下代码准备字符串请求:

Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", edit_username.getText().toString())
                        .appendQueryParameter("password", edit_password.getText().toString());

                    String query = builder.build().getEncodedQuery();

通过以下代码在异步任务中执行所有Web服务:

class AsyncLoad extends AsyncTask<Void,Void,Void>
{

    InputStream inputStream;
    HttpURLConnection urlConnection;
    byte[] outputBytes;
    String query;
    String ResponseData;

    public AsyncLoad(String query) {
        this.query = query;
    }

    @Override
    protected Void doInBackground(Void... params) {

        // Send data
        try {

        /* forming th java.net.URL object */
            URL url = new URL("your webservice url");
            urlConnection = (HttpURLConnection) url.openConnection();


            /* pass post data */
            outputBytes = query.getBytes("UTF-8");

            urlConnection.setRequestMethod("POST");
            urlConnection.connect();
            OutputStream os = urlConnection.getOutputStream();
            os.write(outputBytes);
            os.close();

        /* Get Response and execute WebService request*/
            int statusCode = urlConnection.getResponseCode();

        /* 200 represents HTTP OK */
            if (statusCode == HttpsURLConnection.HTTP_OK) {

                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                ResponseData= convertStreamToString(inputStream);

            } else {

                ResponseData = null;
            }


        } catch (Exception e) {

            e.printStackTrace();

        }



        return null;
    }
}

通过以下行调用AsynctTask:

  new AsyncLoad(query).execute(); // You have pass your request here

将响应转换为String:

public static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

答案 1 :(得分:2)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     new AsyncCaller().execute();
}


private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
    ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);

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

        //this method will be running on UI thread
        pdLoading.setMessage("Loading...");
        pdLoading.show();
    }
    @Override
    protected Void doInBackground(Void... params) {

         String address = "http://server/postvalue";
            JSONObject json = new JSONObject();                
            json.put("username", username);
            json.put("password", password);
            String requestBody = json.toString();
            URL url = new URL(address);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
            writer.write(requestBody);
            writer.flush();
            writer.close();
            outputStream.close();

            InputStream inputStream;
            // get stream
            if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                inputStream = urlConnection.getInputStream();
            } else {
                inputStream = urlConnection.getErrorStream();
            }
            // parse stream
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp, response = "";
            while ((temp = bufferedReader.readLine()) != null) {
                response += temp;
            }

            return response.toString();

        } catch (IOException | JSONException e) {
            return e.toString();
        }

    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);             
        pdLoading.dismiss();
        Log.i(LOG_TAG, "POST\n" + result);
    }

    }
}

答案 2 :(得分:0)

您可以使用Apache Commons的Http Client。例如:

msg.body

答案 3 :(得分:0)

    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(register_user);
    JSONObject jsonObject=new JSONObject();
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    try {

       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("username", username.getText().toString())); 
       params.add(new BasicNameValuePair("password",password.getText().toString())); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 


        HttpResponse response=httpClient.execute(httpPost);


        if(response!=null){
            InputStream is=response.getEntity().getContent();
            BufferedReader bufferedReader=new BufferedReader(new     InputStreamReader(is));
            StringBuilder sb=new StringBuilder();
            String line=null;
            while((line=bufferedReader.readLine())!=null){
                sb.append(line+"\n");
            }
            this.message=sb.toString();
            //Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
        }

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