有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将JSON数据发布到服务器

我正在将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) 个答案