Android HttpClient, DefaultHttpClient, HttpPost

◇◆丶佛笑我妖孽 提交于 2019-11-28 11:23:33

I think in your code the basic problem is caused by the way you are using StringEntity to POST parameters to your url. Check to see if the following code helps in posting your data to the server using StringEntity.

    // Build the JSON object to pass parameters
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("username", username);
    jsonObj.put("data", dataValue);

    // Create the POST object and add the parameters
    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(httpPost);

Hope this helps in solving your problem. Thanks.

Well, here are my thoughts on your question:-

  1. First, you should simply send the data to the server by using POST method. Its easy and absolutely possible in Android also. A simple code snippet for sending POST data can be like:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://yourserverIP/postdata.php");
    String serverResponse = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("datakey1", dataValue1));
        nameValuePairs.add(new BasicNameValuePair("datakey2",
                dataValue2));
    
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
    
        serverResponse = response.getStatusLine().toString();
        Log.e("response", serverResponse);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    The above code sends data to a PHP script postdata on your server.

  2. Next, for parsing the JSON data sent by the server, you can use a JSONParser and then easily utilize it as per your needs. You can get the response returned from the server by using the following code:

    String jsonData = EntityUtils.toString(serverResponse.getEntity());
    

Hope this helps. Thanks.

try using this method where strJsonRequest is the json string you want to post and the strUrl is the url to which you want to post the strJsonRequest

   public String urlPost(String strJsonRequest, String strURL) throws Exception 
{
    try
    {
        URL objURL = new URL(strURL);
        connection = (HttpURLConnection)objURL.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setAllowUserInteraction(false);
        connection.setUseCaches(false);
        connection.setConnectTimeout(TIMEOUT_CONNECT_MILLIS);
        connection.setReadTimeout(TIMEOUT_READ_MILLIS);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept-Charset", "utf-8");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setRequestProperty("Content-Length", ""+strJsonRequest.toString().getBytes("UTF8").length);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        byte [] b = strJsonRequest.getBytes("UTF-8");

        outputStream.write(b);
        outputStream.flush();

        inputstreamObj = (InputStream) connection.getContent();//getInputStream();

        if(inputstreamObj != null)
            strResponse = convertStreamToString(inputstreamObj);

    }
    catch(Exception e)
    {
        throw e;
    }
    return strResponse;
}

and the method convertStreamToString() is as below

private static String convertStreamToString(InputStream is)
{
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    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();
}

Depending on how your server side code is set up, an example format of the url where your server has a php page to handle the API call would be:

http://yoururl.com/demo.php?jsondata=postData

If your are using a post connection you can simply say:

http://yoururl.com/demo.php

and pass it your post parameters i.e. the json string

Here is a great tutorial on how to do this: http://yoururl.com/demo.php?jsondata=postData

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!