附加的JSONData没有发布

时间:2013-09-13 12:24:19

标签: android json http-post

我已经完成了所有相关的线程,但我还没有成功。 我使用下面的代码将JSON发布到服务器。但是JSON数据没有发布到URL。

public static JSONObject PostJSONFromUrl(String urlString , String jsontosend ) 
    {
        Log.e(" Api-Hit urlString " , " is "+urlString);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        JSONObject json = null ;
        String tmpstr ;

        try {
                HttpPost post = new HttpPost(urlString);
                StringEntity se = new StringEntity(jsontosend);  
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                //Checking response 
                if(response!=null)
                {
                    tmpstr = EntityUtils.toString(response.getEntity());
                    json = new JSONObject(tmpstr);
                }
        } 
        catch(Exception e) 
        {
            e.printStackTrace();
        }

        Log.e(" Api-Hit return data " , " is "+json);
        return json;

    }

我不知道我哪里错了。

我从服务器端获取JSON的返回数据。如果发送到服务器的JSON为空,我会收到“无效数据”错误。

先谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

      public class HttpClientService{
private String LOG_TAG = "HttpClientService";
private DefaultHttpClient httpclient;
//private String WEBSERVER_URL = "";

public HttpClientService(final Context context){
    httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(null, -1),
            new UsernamePasswordCredentials("admin","pass"));
}
public JSONObject executeServiceWithParams(final String params) {
    String aURL = WEBSERVER_URL + "?" + params.replace(" ", "%20");
    //aURL = aURL.replace("\n", "");

    aURL = aURL.replace("\n", "?????");
    Log.d(LOG_TAG, "Service = "+ aURL);

    System.out.println("------ Service URL --------"+aURL);

    HttpPost httppost = new HttpPost(aURL);
    try {
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        final InputStream responseStream = response.getEntity().getContent();

        if(responseStream != null){
            final JSONObject result = getJsonObjectFromStream(responseStream);
            return result;
        }
        return null;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.d(LOG_TAG, "exception generated while login "+ e.toString());
    }
    return null;
}