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

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("UserName","example@gmail.com");
        jsonObject.accumulate("Password","123456!");


        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        Toast.makeText(getBaseContext()," text",Toast.LENGTH_SHORT).show();
        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

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

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}
 private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

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

我尝试从 HTTPAsyncTask 类的对象调用此 POST 方法,并传递了目标 url。但是在 OnPostExecute() 中执行的 Toast 会弹出消息“数据已发送!完成”,这表明“结果”变量的值为空。在 log cat 中它显示“我从 logcat 收到反馈“请求时间失败,Java.net.socketException:协议不支持地址系列”。错误是什么?谁能解决这个问题***

4

2 回答 2

0

尝试将此添加到 AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

请抓住这个例外:

catch(SocketException se)
       {
         Log.e("Exception ---- : " , "Error on execute??" + se.getMessage());
           se.printStackTrace();
       }
于 2014-06-09T07:24:30.230 回答
0

URL 缺少协议部分。尝试

http://devcare.dyndns.info:85/WCFServices/UserAuthServices.svc/Login

否则devcare.dyndns.info会被误认为是协议。

于 2014-06-09T07:26:44.707 回答