使用OkHttp访问API时收到空响应。

huangapple go评论97阅读模式
英文:

Getting Null Response while using OkHttp to hit an API

问题

@SuppressLint("StaticFieldLeak")
public class OkHttpHandler extends AsyncTask<RequestItem, String, String> {
    
    OkHttpClient client = new OkHttpClient();
    
    @Override
    protected String doInBackground(RequestItem... params) {
        JSONObject object;
        RequestItem requestItem = params[0];
        JSONObject data = requestItem.object;
        
        object = new JSONObject();
        try {
            object.put("school_id", data.getInt("school_id"));
            object.put("batch_id", data.getInt("batch_id"));
            object.put("category", data.getInt("category"));
            object.put("subject", data.getString("subject"));
            object.put("due_date", data.getString("due_date"));
            object.put("repeat", data.getInt("repeat"));
            object.put("priority", data.getInt("priority"));
            object.put("description", data.getString("description"));
            object.put("additional_detail", data.getString("additional_details"));
            object.put("file_url", data.getString("file_url"));
            
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody json = RequestBody.create(object.toString(), JSON);
            Request.Builder builder = new Request.Builder();
            builder.url(requestItem.url)
                .method("POST", json)
                .addHeader("Cookie", "__cfduid=d5209babc31d5f41904fce0f542568e4e1591610891");
            Request request = builder.build();
            
            try {
                Response response = client.newCall(request).execute();
                return Objects.requireNonNull(response.body()).string();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("AddHW", "error:" + e.getMessage());
        }
        return null;
    }
    
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        try {
            JSONObject object = new JSONObject(s);
            if (object.getString("status").equals("OK")) {
                JSONObject res = object.getJSONObject("results");
                Toast.makeText(AddHW.this, "" + res.getString("message"), Toast.LENGTH_SHORT).show();
                Log.d("addHw", "response: " + res.getString("message"));
                show_add_homeWork();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("error", "error:" + e.getMessage());
        }
    }
}
英文:

I am trying to hit an API using OkHttp since Volley won't let put the body data in multipart, if it could then I don't know how to do, so when I'm using this everything works the data is being sent, but I am constantly getting my response as null or ZERO . I tried hit the API using Postman it works perfect and then I put the same data static is my code and then run it ,still the same response.

The data is put using JSONobject

@SuppressLint( &quot;StaticFieldLeak&quot; )
public class OkHttpHandler extends AsyncTask &lt; RequestItem, String, String &gt; {
OkHttpClient client = new OkHttpClient();
@Override
protected String doInBackground(RequestItem... params) {
JSONObject object;
RequestItem requestItem = params[ 0 ];
JSONObject data = requestItem.object;
Toast.makeText( AddHW.this, &quot;dta&quot;+data, Toast.LENGTH_SHORT ).show( );
Log.d( &quot;data&quot;, &quot;data&quot; + data );
//MediaType mediaType = MediaType.parse( &quot;text/plain&quot; );
object = new JSONObject();
try {
object.put( &quot;school_id&quot;, data.getInt( &quot;school_id&quot; ) );
object.put( &quot;batch_id&quot;, data.getInt( &quot;batch_id&quot; ) );
object.put( &quot;category&quot;, data.getInt( &quot;category&quot; ) );
object.put( &quot;subject&quot;, data.getString( &quot;subject&quot; ) );
object.put( &quot;due_date&quot;, data.getString( &quot;due_date&quot; ) );
object.put( &quot;repeat&quot;, data.getInt( &quot;repeat&quot; ) );
object.put( &quot;priority&quot;, data.getInt( &quot;priority&quot; ) );
object.put( &quot;description&quot;, data.getString( &quot;description&quot; ) );
object.put( &quot;additional_detail&quot;, data.getString( &quot;additional_details&quot; ) );
object.put( &quot;file_url&quot;, data.getString( &quot;file_url&quot; ) );
MediaType JSON = MediaType.parse( &quot;application/json; charset=utf-8&quot; );
RequestBody json = RequestBody.create( object.toString(), JSON );
Request.Builder builder = new Request.Builder();
builder.url( requestItem.url )
.method( &quot;POST&quot;, body )
.post( json );
.addHeader( &quot;Cookie&quot;, &quot;__cfduid=d5209babc31d5f41904fce0f542568e4e1591610891&quot; );
Request request = builder.build();
try {
Response response = client.newCall( request ).execute();
return Objects.requireNonNull( response.body() ).string();
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (JSONException e) {
e.printStackTrace();
Log.d( &quot;AddHW &quot;, &quot;error:&quot; + e.getMessage() );
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute( s );
try {
JSONObject object = new JSONObject( s );
if ( object.getString( &quot;status&quot; ).equals( &quot;OK&quot; ) ) {
JSONObject res = object.getJSONObject( &quot;results&quot; );
Toast.makeText( AddHW.this, &quot;&quot; + res.getString( &quot;message&quot; ), Toast.LENGTH_SHORT ).show( );
Log.d( &quot;addHw&quot;, &quot;response: &quot; + res.getString( &quot;message&quot; ) );
show_add_homeWork( );
}
} catch ( JSONException e ) {
e.printStackTrace( );
Log.d( &quot;error&quot;, &quot;error:&quot; + e.getMessage( ) );
}
}
}

答案1

得分: 0

这可能有助于您解决问题,

我注意到您已经使用了.method("POST", body),但我没有找到任何body,可能是因为显示的代码不足,或者它是一个全局变量之类的东西,但我看到您从对象(JSON对象)中创建了一个RequestBody,其中我认为您正在将用户数据存储在其中(我希望是这样),然后将其放入.post(json),这应该可以工作,并且您应该能够得到您正在寻找的响应。

还有一件事,我不认为您应该使用

.addHeader("Cookie", "__cfduid=d5209babc31d5f41904fce0f542568e4e1591610891")

因为这可能是不必要的,并且可能会干扰您的后端。希望这回答了您的问题。

英文:

This may help You solve your issue ,

I noticed that you have used the .method( &quot;POST&quot;, body ) and I couldn't find any body may be due to insufficient code shown or may be it is a global variable or something , but I see you creating a Requestbody from the object (JSONobject) in which i think you are storing your data from the user ( I hope so), and putting it in the .post(json), which should work and you should get the Response you are looking for.

One more thing I don't think you should use the

> .addHeader( "Cookie", "__cfduid=d5209babc31d5f41904fce0f542568e4e1591610891" )

since this is kinda unnecessary and might be interfering with your backend.
Hope this answers your question .

huangapple
  • 本文由 发表于 2020年6月29日 12:54:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/62631441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定