java - 在android代码中没有得到web服务的响应

标签 java android ios objective-c web-services

我正在开发一个应用程序,因为我已经开发了用于调用 web 服务的 ios 代码,它成功地给我响应,当我尝试在 android 中调用时,相同的 web 服务调用它不工作它没有给我回复,我正在发布我的两个代码,有人可以帮我弄清楚吗?

ios代码

  NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",k_SERVER_BASE_ADDRESS,service_name]];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    // 2
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    request.HTTPMethod = @"POST";

    [request setValue:[NSString stringWithFormat:@"%@",k_CONTENT_TYPE] forHTTPHeaderField:@"Content-Type"];

    // 3
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setObject:[NSString stringWithFormat:@"%@",k_USER_NAME] forKey:@"APIUserName"];
    [dictionary setObject:[NSString stringWithFormat:@"%@",k_PASSWORD] forKey:@"Password"];

    NSLog(@"%@",dictionary);
    NSError *error = nil;
    NSData *data_prm = [NSJSONSerialization dataWithJSONObject:dictionary
                                                       options:kNilOptions error:&error];

    NSLog(@"%@",[[NSString alloc] initWithData:data_prm encoding:NSUTF8StringEncoding]);
    if (!error) {
        // 4
        NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
                                                                   fromData:data_prm completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
                                                                       // Handle response here..

                                                                       NSLog(@"this is data : %@",data);

安卓代码

public class GETCONTESTANTS extends AsyncTask<Void, Void, Void> {

    StringEntity se;
        @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(StartActivity.this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(false);
        pDialog.show();
        // stateList.clear();


    }

    @Override
    protected Void doInBackground(Void... params) {

        HttpClient httpClient = new DefaultHttpClient();


        HttpPost httpPost = new HttpPost("http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants");
          String json = "";
          try {
          // 3. build jsonObject
          JSONObject jsonObject = new JSONObject();
          jsonObject.accumulate("APIUserName", "AFBK8@DL4EJMd6");
          jsonObject.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
                   // 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


            se = new StringEntity(json);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

          // 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");

        try {

             HttpResponse httpResponse = httpClient.execute(httpPost);

             // 9. receive response as inputStream
             inputStream = httpResponse.getEntity().getContent();

在上面的代码中,“iOS 代码”工作正常,“android 代码”不工作。谁能帮帮我?

最佳答案

尝试这段代码可能会有帮助

public class JSONParser {
    static InputStream is = null;
    static JSONObject jobj = null;
    static String json = "";
    String url="http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants";

    public JSONParser(){

    }


   public JSONObject makeHttpRequest(String url){

    JSONObject jo = null;
    jo = new JSONObject();

    try {
         jo.accumulate("APIUserName", "AFBK8@DL4EJMd6");
      jo.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject job=new JSONObject();
    try {
        job.accumulate("aloha", jo);
    } catch (JSONException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    Log.e("url", job.toString());
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(this.url);
        try {
            httppost.setEntity(new StringEntity(job.toString(), "UTF-    8"));

           //               httppost.toString();
        //              Log.e("url", httppost.toString());
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            HttpResponse httpresponse = httpclient.execute(httppost);
            HttpEntity httpentity = httpresponse.getEntity();
            is = httpentity.getContent();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new   InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while((line = reader.readLine())!=null){
                    sb.append(line+"\n");   

                }
                is.close();
                json = sb.toString();
                Log.e("url", json);
                try {
                    jobj = new JSONObject(json);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    return jobj;

     }

关于java - 在android代码中没有得到web服务的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38306720/

相关文章:

ios - 从 applicationwillresignactive 中调用函数

iphone - 当单选按钮选择检查

android - adb devices - 设备不断增加

java.lang.SecurityException 不允许从另一个 Android 应用程序安装 apk

iphone - 将 UIView 添加到另一个 UIView 作为 SubView

java - 如何在 Java 中比较字符串和枚举类型?

Android:如何在另一个布局的 XML 中使用样式中的颜色

java - sqlite3查询安卓

java - eclipse,动态Web项目,将另一个eclipse项目添加到类路径

java - TestNG:如何在通用函数中验证测试结果