我已经使用Http进行网络请求但http现在很慢我想使用okhttp而不是http如何将http转换为okhttp我的代码在下面
public class Http {
public String postRequest(String endPoint, String body) {
URL url;
Log.d("Waseem", "Calling URL:" + endPoint);
HttpURLConnection connection = null;
String response = "";
try {
url = new URL(endPoint);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//send data to server over the connection.
OutputStream outputStream = connection.getOutputStream();
outputStream.write(body.getBytes());
outputStream.flush();
outputStream.close();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseLine;
while ((responseLine = bufferedReader.readLine()) != null) {
// Log.d(MainActivity.LOG_TAG,"Response: "+responseLine);
response += responseLine;
}
//Log.d(MainActivity.LOG_TAG,"Response: "+response);
connection.disconnect();
} catch (Exception exp) {
//Log.d(MainActivity.LOG_TAG,"Exception: "+exp.getMessage());
exp.printStackTrace();
response = "{\"result\":false,\"message\":\"Exception: " + exp.getMessage() + "\"}";
}
if (connection != null) {
connection.disconnect();
}
return response;
}
这是我发过http请求的java活动,如何将此代码更改为ok http
private Http http;
private String remoteMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailLogin= (EditText) findViewById(R.id.etEmailLog);
passwordLogin= (EditText) findViewById(R.id.etPassLog);
http=new Http();
login= (TextView) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (emailLogin.getText().toString().length()>3 &&
passwordLogin.getText().toString().length()>4){
emailText=emailLogin.getText().toString();
passwordText=passwordLogin.getText().toString();
new AsyncTask<Void, Integer, String>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
//progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(Void... params) {
String response;
String body="email="+emailText+"&password="+passwordText;
response=http.postRequest(HttpConfigs.URL_AUTH,body);
return response;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
final JSONObject responseJson = new JSONObject(response);
remoteMessage=responseJson.getString("message");
if (responseJson.getBoolean("result")){
showMessage(remoteMessage);
JSONObject data = responseJson.getJSONObject("data");
Log.d("WaseemTest","Data"+data);
}else{
showMessage(remoteMessage);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}.execute();
}
}
});
}
答案 0 :(得分:0)
首先导入okhttp库
import okhttp3.OkHttpClient;
然后创建一个okhttp类,您将为每个http请求调用
public class InitializeBuilderOkhttp extends OkHttpClient{
OkHttpClient client;
public OkHttpClient returnInitializeBuilderOkhttp() {
client = new OkHttpClient();
Builder builder = new Builder();
builder.connectTimeout(0, TimeUnit.SECONDS);
builder.readTimeout(0, TimeUnit.SECONDS);
builder.writeTimeout(0, TimeUnit.SECONDS);
client = builder.build();
return client;
}
}
请通过okhttp教程了解为什么在这种情况下超时是这样的。你可以根据自己的喜好进行更改。
然后在活动中,
OkHttpClient client;
client = new InitializeBuilderOkhttp().returnInitializeBuilderOkhttp();
Request request = new Request.Builder()
.url(urlOrders+parameterStringBeforeEncoding+"&oauth_signature="+signature)
.get()
.build();
Response response = null;
try{
response = client.newCall(request).execute();
}
catch (ConnectException ex){
//Toast.makeText(this_context,"Cannot connect to server at this time.Please try again later",Toast.LENGTH_LONG).show();
}
//Log.d("output",""+result);
if (response != null) {
return response.body().string();
}
这将出现在异步任务中&#34;在后台&#34;在您的情况下,请求将是POST类型。
对于帖子类型,
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
okhttp3.RequestBody body = RequestBody.create(JSON, postDataStringInJson);
okhttp3.Request request = new okhttp3.Request.Builder()
.url(urlOrders+parameterStringBeforeEncoding+"&oauth_signature="+signature)
.post(body)
.build();
如有任何疑问请发表评论。