-1

我已经完成了所有相关的线程,但我还没有成功。我使用以下代码将 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 为空,我会收到应该接收的“无效数据”错误。

提前致谢 。

4

1 回答 1

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;
}
于 2013-09-13T12:30:17.943 回答