use of okhttp3.RequestBody in project Gradle-demo by Arisono.
the class OkhttpUtilsMain method sendFormParams.
/**
* 表单提交
*/
public static void sendFormParams() {
Map<String, Object> publicMap = RSAEncodeToken();
String miwen = (String) publicMap.get("miwen");
String public_key = (String) publicMap.get("public_key");
RequestBody formBody = new FormBody.Builder().add("username", "123").add("password", "df13edafsdddsads").add("publicKey", public_key).add("miwen", miwen).build();
//postBody 接收
String json_1 = "{}";
@SuppressWarnings("unused") String bytes = "username=123&password=df13edafsdddsads";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://localhost:8080/spring-mvc-showcase/http/getHeaders").header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D").addHeader("content-type", "text/html;charset:utf-8").post(RequestBody.create(JSONTYPE, json_1)).post(formBody).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String json = response.body().string();
System.out.println(json);
} else {
System.out.println(JSON.toJSONString(response.code()));
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("******************************************************");
}
use of okhttp3.RequestBody in project Gradle-demo by Arisono.
the class RetrofitUtils method uploads.
public void uploads(Subscriber<Object> s, String url, Map<String, Object> params) {
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
//追加参数
for (String key : params.keySet()) {
Object object = params.get(key);
if (!(object instanceof File)) {
builder.addFormDataPart(key, object.toString());
} else {
File file = (File) object;
//其中参数“file”和服务器接收的参数 一一对应,保证多文件上传唯一key不变
builder.addFormDataPart("file", file.getName(), RequestBody.create(null, file));
}
}
//创建RequestBody
RequestBody body = builder.build();
Observable<Object> o = paramService.uploads(url, body);
toSubscribe(o, s);
}
use of okhttp3.RequestBody in project PokeGOAPI-Java by Grover-c13.
the class RequestHandler method sendInternal.
/**
* Sends an already built request envelope
*
* @param serverResponse the response to append to
* @param requests list of ServerRequests to be sent
* @param platformRequests list of ServerPlatformRequests to be sent
* @param builder the request envelope builder
* @throws RequestFailedException if this message fails to send
*/
private ServerResponse sendInternal(ServerResponse serverResponse, ServerRequest[] requests, ServerPlatformRequest[] platformRequests, RequestEnvelope.Builder builder) throws RequestFailedException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
RequestEnvelope request = builder.build();
try {
request.writeTo(stream);
} catch (IOException e) {
Log.wtf(TAG, "Failed to write request to bytearray ouput stream. This should never happen", e);
}
RequestBody body = RequestBody.create(null, stream.toByteArray());
okhttp3.Request httpRequest = new okhttp3.Request.Builder().url(apiEndpoint).post(body).build();
try (Response response = client.newCall(httpRequest).execute()) {
if (response.code() != 200) {
throw new RequestFailedException("Got a unexpected http code : " + response.code());
}
ResponseEnvelope responseEnvelop;
try (InputStream content = response.body().byteStream()) {
responseEnvelop = ResponseEnvelope.parseFrom(content);
} catch (IOException e) {
// retrieved garbage from the server
throw new RequestFailedException("Received malformed response : " + e);
}
if (responseEnvelop.getApiUrl() != null && responseEnvelop.getApiUrl().length() > 0) {
apiEndpoint = "https://" + responseEnvelop.getApiUrl() + "/rpc";
}
if (responseEnvelop.hasAuthTicket()) {
this.authTicket = responseEnvelop.getAuthTicket();
}
boolean empty = false;
StatusCode statusCode = responseEnvelop.getStatusCode();
if (statusCode != StatusCode.REDIRECT && statusCode != StatusCode.INVALID_AUTH_TOKEN) {
for (int i = 0; i < responseEnvelop.getReturnsCount(); i++) {
ByteString returned = responseEnvelop.getReturns(i);
ServerRequest serverRequest = requests[i];
if (returned != null) {
serverResponse.addResponse(serverRequest.getType(), returned);
if (serverRequest.getType() == RequestType.GET_PLAYER) {
if (GetPlayerResponse.parseFrom(returned).getBanned()) {
throw new BannedException("Cannot send request, your account has been banned!");
}
}
} else {
empty = true;
}
}
}
for (int i = 0; i < responseEnvelop.getPlatformReturnsCount(); i++) {
PlatformResponse platformResponse = responseEnvelop.getPlatformReturns(i);
ByteString returned = platformResponse.getResponse();
if (returned != null) {
serverResponse.addResponse(platformResponse.getType(), returned);
}
}
if (statusCode != StatusCode.OK && statusCode != StatusCode.OK_RPC_URL_IN_RESPONSE) {
if (statusCode == StatusCode.INVALID_AUTH_TOKEN) {
try {
authTicket = null;
api.getAuthInfo(true);
return sendInternal(serverResponse, requests, platformRequests);
} catch (LoginFailedException | InvalidCredentialsException e) {
throw new RequestFailedException("Failed to refresh auth token!", e);
} catch (RequestFailedException e) {
throw new RequestFailedException("Failed to send request with refreshed auth token!", e);
}
} else if (statusCode == StatusCode.REDIRECT) {
// API_ENDPOINT was not correctly set, should be at this point, though, so redo the request
return sendInternal(serverResponse, requests, platformRequests, builder);
} else if (statusCode == StatusCode.BAD_REQUEST) {
if (api.getPlayerProfile().isBanned()) {
throw new BannedException("Cannot send request, your account has been banned!");
} else {
throw new BadRequestException("A bad request was sent!");
}
} else {
throw new RequestFailedException("Failed to send request: " + statusCode);
}
}
if (empty) {
throw new RequestFailedException("Received empty response from server!");
}
} catch (IOException e) {
throw new RequestFailedException(e);
} catch (RequestFailedException e) {
throw e;
}
return serverResponse;
}
use of okhttp3.RequestBody in project PokeGOAPI-Java by Grover-c13.
the class GoogleCredentialProvider method login.
/**
* Starts a login flow for google using googles device oauth endpoint.
*
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public void login() throws LoginFailedException, InvalidCredentialsException {
HttpUrl url = HttpUrl.parse(OAUTH_ENDPOINT).newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("scope", "openid email https://www.googleapis.com/auth/userinfo.email").build();
//Create empty body
RequestBody reqBody = RequestBody.create(null, new byte[0]);
Request request = new Request.Builder().url(url).method("POST", reqBody).build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
throw new LoginFailedException("Network Request failed to fetch tokenId", e);
}
Moshi moshi = new Moshi.Builder().build();
GoogleAuthJson googleAuth = null;
try {
googleAuth = moshi.adapter(GoogleAuthJson.class).fromJson(response.body().string());
Log.d(TAG, "" + googleAuth.getExpiresIn());
} catch (IOException e) {
throw new LoginFailedException("Failed to unmarshell the Json response to fetch tokenId", e);
}
Log.d(TAG, "Get user to go to:" + googleAuth.getVerificationUrl() + " and enter code:" + googleAuth.getUserCode());
onGoogleLoginOAuthCompleteListener.onInitialOAuthComplete(googleAuth);
GoogleAuthTokenJson googleAuthTokenJson;
try {
while ((googleAuthTokenJson = poll(googleAuth)) == null) {
Thread.sleep(googleAuth.getInterval() * 1000);
}
} catch (InterruptedException e) {
throw new LoginFailedException("Sleeping was interrupted", e);
} catch (IOException e) {
throw new LoginFailedException(e);
} catch (URISyntaxException e) {
throw new LoginFailedException(e);
}
Log.d(TAG, "Got token: " + googleAuthTokenJson.getIdToken());
onGoogleLoginOAuthCompleteListener.onTokenIdReceived(googleAuthTokenJson);
expiresTimestamp = System.currentTimeMillis() + (googleAuthTokenJson.getExpiresIn() * 1000 - REFRESH_TOKEN_BUFFER_TIME);
tokenId = googleAuthTokenJson.getIdToken();
refreshToken = googleAuthTokenJson.getRefreshToken();
}
use of okhttp3.RequestBody in project PokeGOAPI-Java by Grover-c13.
the class PtcCredentialProvider method login.
/**
* Starts a login flow for pokemon.com (PTC) using a username and password,
* this uses pokemon.com's oauth endpoint and returns a usable AuthInfo without user interaction
*
* @param username PTC username
* @param password PTC password
* @param attempt the current attempt index
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
private void login(String username, String password, int attempt) throws LoginFailedException, InvalidCredentialsException {
try {
//TODO: stop creating an okhttp client per request
Request get = new Request.Builder().url(LOGIN_URL).get().build();
Response getResponse;
try {
getResponse = client.newCall(get).execute();
} catch (IOException e) {
throw new LoginFailedException("Failed to receive contents from server", e);
}
Moshi moshi = new Moshi.Builder().build();
PtcAuthJson ptcAuth;
try {
String response = getResponse.body().string();
ptcAuth = moshi.adapter(PtcAuthJson.class).fromJson(response);
} catch (IOException e) {
throw new LoginFailedException("Looks like the servers are down", e);
}
HttpUrl url = HttpUrl.parse(LOGIN_URL).newBuilder().addQueryParameter("lt", ptcAuth.getLt()).addQueryParameter("execution", ptcAuth.getExecution()).addQueryParameter("_eventId", "submit").addQueryParameter("username", username).addQueryParameter("password", password).build();
RequestBody reqBody = RequestBody.create(null, new byte[0]);
Request postRequest = new Request.Builder().url(url).method("POST", reqBody).build();
// Need a new client for this to not follow redirects
Response response;
try {
response = client.newBuilder().followRedirects(false).followSslRedirects(false).build().newCall(postRequest).execute();
} catch (IOException e) {
throw new LoginFailedException("Network failure", e);
}
String body;
try {
body = response.body().string();
} catch (IOException e) {
throw new LoginFailedException("Response body fetching failed", e);
}
if (body.length() > 0) {
PtcError ptcError;
try {
ptcError = moshi.adapter(PtcError.class).fromJson(body);
} catch (IOException e) {
throw new LoginFailedException("Unmarshalling failure", e);
}
if (ptcError.getError() != null && ptcError.getError().length() > 0) {
throw new InvalidCredentialsException(ptcError.getError());
} else if (ptcError.getErrors().length > 0) {
StringBuilder builder = new StringBuilder();
String[] errors = ptcError.getErrors();
for (int i = 0; i < errors.length - 1; i++) {
String error = errors[i];
builder.append("\"").append(error).append("\", ");
}
builder.append("\"").append(errors[errors.length - 1]).append("\"");
throw new InvalidCredentialsException(builder.toString());
}
}
String ticket = null;
for (String location : response.headers("location")) {
String[] ticketArray = location.split("ticket=");
if (ticketArray.length > 1) {
ticket = ticketArray[1];
}
}
if (ticket == null) {
throw new LoginFailedException("Failed to fetch token, body:" + body);
}
url = HttpUrl.parse(LOGIN_OAUTH).newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("redirect_uri", REDIRECT_URI).addQueryParameter("client_secret", CLIENT_SECRET).addQueryParameter("grant_type", "refreshToken").addQueryParameter("code", ticket).build();
postRequest = new Request.Builder().url(url).method("POST", reqBody).build();
try {
response = client.newCall(postRequest).execute();
} catch (IOException e) {
throw new LoginFailedException("Network Failure ", e);
}
try {
body = response.body().string();
} catch (IOException e) {
throw new LoginFailedException("Network failure", e);
}
String[] params;
try {
params = body.split("&");
int expire = Integer.valueOf(params[1].split("=")[1]);
tokenId = params[0].split("=")[1];
expiresTimestamp = time.currentTimeMillis() + (expire * 1000 - REFRESH_TOKEN_BUFFER_TIME);
unknown2 = expire;
if (random.nextDouble() > 0.1) {
unknown2 = UK2_VALUES[random.nextInt(UK2_VALUES.length)];
}
} catch (Exception e) {
throw new LoginFailedException("Failed to fetch token, body:" + body);
}
} catch (LoginFailedException e) {
if (shouldRetry && attempt < MAXIMUM_RETRIES) {
login(username, password, ++attempt);
}
}
}
Aggregations