morristech
3/28/2019 - 1:00 PM

Connect to server with okHttp + mimecraft

Connect to server with okHttp + mimecraft

public abstract class API {
  private static BackendResponse getResponseWithOKHttp(Context context, Request req,
  		List<NameValuePair> nvp, boolean hasMedia) {
		if (req != Request.DEVICE_CREATE && !Utils.deviceIsCreated(context)) {
			// NOTE Houston, We've Got a Problem, try again!
			BackendResponse br = createDevice(context, null);
			if (br.isOK()) {
				Utils.storeTokens(context, br.getJSON());
			} else {
				return br;
			}
		}

		OkHttpClient client = new OkHttpClient();

		String url = context.getResources().getString(R.string.host) + req.getPath();

		switch (req.getMethod()) {
		case GET:
			if (nvp != null && nvp.size() > 0) {
				url += "?" + Utils.getUrlEncodedString(nvp);
			}

			if (BuildConfig.DEBUG) {
				Log.d(DingDongApp.TAG, url);
			}
			return BackendResponse.createOKHttpGET(client, url, req);
		case POST:
			Builder m = new Multipart.Builder();
			if (hasMedia) {
				for (int index = 0; index < nvp.size(); index++) {
					if (nvp.get(index).getName().equalsIgnoreCase(API.IMAGE)) {
						File image = new File(nvp.get(index).getValue());
						m.addPart(
								new Part.Builder()
										.contentType("image/jpeg")
										.body(image)
										.contentDisposition(
												"form-data; name=\"image\"; filename=\""
														+ image.getName()
														+ "\"")
										.contentEncoding("binary")
										.build());

					} else {
						m.addPart(new Part.Builder()
								.contentType("text/plain; charset=UTF-8")
								.body(nvp.get(index).getValue())
								.contentDisposition(
										"form-data; name=\"" + nvp.get(index).getName() + "\";")
								.contentEncoding("8bit")
								.build());

					}
				}
				Multipart multiPart = m.build();
				return BackendResponse.createOKHttpMulti(client, multiPart, url, req);
			} else {
				com.squareup.mimecraft.FormEncoding.Builder fe = new FormEncoding.Builder();
				for (int index = 0; index < nvp.size(); index++) {
					String key = nvp.get(index).getName();
					String value = nvp.get(index).getValue();
					fe.add(key, value);
				}
				FormEncoding formEncoding = fe.build();

				return BackendResponse.createOKHttpForm(client, formEncoding, url, req);
			}

		default:
			return null;
		}
	}
}
public class BackendResponse {
  public static BackendResponse createOKHttpForm(OkHttpClient client, FormEncoding formEncoding, String url, Request req) {
		HttpURLConnection connection;
		JSONObject json = null;
		try {
			connection = client.open(new URL(url));

			// Set header of request if path on url is not /device/create
			if (req != Request.DEVICE_CREATE) {
				setAutherization(connection);
				String userAgent = API.getUserAgent(MyApplication.getContext());
				connection.addRequestProperty("User-Agent", userAgent);
				connection.addRequestProperty("Local-Time", Utils.LOCAL_FORMAT.format(new Date()));
				connection.addRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
			}
			for (Map.Entry<String, String> entry : formEncoding.getHeaders().entrySet()) {
				connection.addRequestProperty(entry.getKey(), entry.getValue());
			}

			connection.addRequestProperty("Accept", API.API_VERSION);

			// Write the request.
			connection.setRequestMethod("POST");
			formEncoding.writeBodyTo(connection.getOutputStream());

			Log.d(TAG, connection.getResponseCode() + " " + connection.getResponseMessage());
			int responseCode = connection.getResponseCode();
			if (responseCode == OK) {
				json = readResponse(connection.getInputStream());
			} else {
				StringBuilder sb;
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				String line;
				sb = new StringBuilder();
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				Log.d(DingDongApp.TAG, sb.toString());
			}

			return new BackendResponse(responseCode, json);
		} catch (ProtocolException e) {
			return new BackendResponse(ERROR, Utils.exceptionToJSON(e));
		} catch (IOException e) {
			return new BackendResponse(ERROR, Utils.exceptionToJSON(e));
		}
	}
}