Я новичок в Java / Android, и мне нужно отправить http-запрос в веб-сервис, чтобы получить ключи (я отправляю дату и получаю ключи).
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpsPostRequest extends AsyncTask<Void, Void, String> {
private Context context;
private String content; //Body
private String request;
protected static ProgressDialog progressDialog = null;
public HttpsPostRequest(Context context, String request, String content) {
this.context = context;
this.request = request;
this.content = content;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(context, "Sending informations", "Please wait ...", false, false);
}
@Override
protected String doInBackground(Void... voids) {
InputStream inputStream = null;
HttpsURLConnection urlConnection = null;
StringBuffer json = null;
try {
URL url = new URL(request);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(true); // indicates POST method
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
int reponse = urlConnection.getResponseCode();
if (reponse != 200)
return "Error";
inputStream = urlConnection.getInputStream();
if (inputStream == null)
return "Error";
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
json = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
json.append(line);
json.append("\n");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ignored) { }
}
}
if (json == null)
return "Error";
if (new String(json).contains("{\"success\":true"))
return new String(json);
return "Error";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
Проблема заключается в следующем: сервер возвращает ответ «GET» на этот запрос, даже если я говорю, что это «POST», и когда я пытаюсь проверить свой запрос с помощью RESTClient, он возвращает хороший ответ. Так что мне нужна твоя помощь, я что-то забыл?