将JSON数据POST到服务器

时间:2018-04-04 16:48:36

标签: java android json json-server

我正在研究POST JSON数据到服务器。它正在使用教程this link正常工作,但它不能与this一起使用一些必需的数据更改。是否存在与Javaservlet和PHP链接相关的任何内容,因为第一个链接是使用Javasevlet设计的,另一个是使用PHP设计的?

public static String POST(String url)
{
    InputStream inputStream = null;
    String result = "";

    try {
        org.apache.http.client.HttpClient httpClient=new DefaultHttpClient();
        HttpPost httpPost=new HttpPost(url);
        String json = "";

        JSONObject jsonObject=new JSONObject();
        /*JSONArray jsonArray=jsonObject.getJSONArray("object");
        JSONObject jsonObject2=jsonArray.getJSONObject(10);*/
        jsonObject.putOpt("id",2);
        jsonObject.putOpt("address","myaddress");

        json=jsonObject.toString();
        StringEntity se=new StringEntity(json);
        httpPost.setEntity(se);

        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse httpResponse=httpClient.execute(httpPost);

        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

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

}

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

       // person = new PersonLocator();
       // person.setAddresS(myLocationText.getText().toString());

        return POST(urls[0]);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
    }
}

感谢您的帮助

0 个答案:

没有答案