I can send notifications to my Android application using another 3rd party server, I can also send notifications from the firebase console, however this servlet (code below) is not sending a notification although the HTTP POST to FCM results in a successful 200 return message.
I think the servlet does not contain code that creates a notification and I am not sure where to exactly create this code. I would like some input.
#WebServlet("/NPS_Servlet")
public class NPS_Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static HashMap<String, Confirmation> TFA = new HashMap<String, Confirmation>();
/**
* #see HttpServlet#HttpServlet()
*/
public NPS_Servlet() {
super();
System.out.println("Servlet gestart");
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
NPS_Servlet Servlet = new NPS_Servlet();
Servlet.processAuthenticate(null, null);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
InputStreamReader isr_Json_Request = null;
isr_Json_Request = new InputStreamReader(request.getInputStream());
ByteArrayOutputStream baos_Json_Request = new ByteArrayOutputStream();
int byteRead = 0;
do {
byteRead = 0;
byteRead = isr_Json_Request.read();
if (byteRead >= 0) {
baos_Json_Request.write(byteRead);
}
} while (byteRead >= 0);
String s_Json_Request = baos_Json_Request.toString();
String s_RequestURI = request.getRequestURI();
String s_ContextPath = request.getContextPath();
String s_Request_Prefix = s_ContextPath;
String s_Request = s_RequestURI.substring(s_Request_Prefix.length(), s_RequestURI.length());
if (! s_Request.startsWith("/")) {
s_Request = "/" + s_Request;
}
System.out.println("Request: " + s_Request);
String s_Response = "";
if (s_Request.equals("/TFA_Servlet_Rami_FinalTake/authenticate")) {
s_Response = handleAuthenticate(s_Json_Request);
}
else if (s_Request.equals("/TFA_Servlet_Rami_FinalTake/confirm")) {
s_Response = handleConfirm(s_Json_Request);
}
System.out.println("Response: " + s_Response);
response.getWriter().print(s_Response);
}
private String handleAuthenticate(String s_Json_Request) {
String s_Json_Response = "";
Gson _Gson = new Gson();
Message json_Request = _Gson.fromJson(s_Json_Request,
Message.class);
if (json_Request != null) {
if (json_Request.getFunction().equals("authenticate")) {
Message json_Response;
try {
json_Response = (Message) json_Request.clone();
processAuthenticate(json_Request, json_Response);
s_Json_Response = _Gson.toJson(json_Response);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
if (s_Json_Response.isEmpty()) {
s_Json_Response = "{ \"result\":1 }";
}
return s_Json_Response;
}
private void processAuthenticate(Message json_Request, Message json_Response){
String s_RegistrationId = "AAAA-NCJai&*******9n&&&****f3gRYjH7*******Nh***********PsedxBhKsrFCuF";
String s_ApiKey = "AIz************EM";
String uniqueID = UUID.randomUUID().toString();;
String s_Data = "";
try {
s_Data = "{" +
"\"data\": {" +
"\"url\": \"http://" + InetAddress.getLocalHost().getHostAddress() + ":8080/TFA_Servlet/confirm\"," +
"\"id\": \"" + uniqueID + "\"" +
"}," +
"\"to\": \"" + s_RegistrationId + "\"" +
"}";
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
try {
URL _URL = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection _HttpURLConnection = (HttpURLConnection) _URL.openConnection();
_HttpURLConnection.setRequestMethod("POST");
_HttpURLConnection.setRequestProperty("Content-Type", "application/json");
_HttpURLConnection.setRequestProperty("Authorization", "key=" + s_RegistrationId);
_HttpURLConnection.setDoOutput(true);
DataOutputStream _DataOutputStream = new DataOutputStream(_HttpURLConnection.getOutputStream());
_DataOutputStream.writeBytes(s_Data);
_DataOutputStream.flush();
_DataOutputStream.close();
int responseCode = _HttpURLConnection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + _URL);
System.out.println("Response Code : " + responseCode);
BufferedReader _BufferedReader = new BufferedReader(
new InputStreamReader(_HttpURLConnection.getInputStream()));
String inputLine;
StringBuffer Response = new StringBuffer();
while ((inputLine = _BufferedReader.readLine()) != null) {
Response.append(inputLine);
}
_BufferedReader.close();
if (responseCode == 200) {
System.out.println("succes");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String handleConfirm(String s_Json_Request) {
String s_Json_Response = "";
Gson _Gson = new Gson();
Message json_Request = _Gson.fromJson(s_Json_Request,
Message.class);
if (json_Request != null) {
if (json_Request.getFunction().equals("confirm")) {
Message json_Response;
try {
json_Response = (Message) json_Request.clone();
processConfirm(json_Request, json_Response);
s_Json_Response = _Gson.toJson(json_Response);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
if (s_Json_Response.isEmpty()) {
s_Json_Response = "{ \"result\":1 }";
}
return s_Json_Response;
}
private void processConfirm(Message json_Request, Message json_Response) {
String s_NotificationId = json_Request.getNotificationId();
String s_Confirmation = json_Request.getConfirmation();
Confirmation _Confirmation = null;
synchronized (TFA) {
_Confirmation = TFA.get(s_NotificationId);
if (TFA != null) {
_Confirmation.setReplied(true);
if (s_Confirmation.equals("approved")) {
_Confirmation.setConfirmed(true);
}
json_Response.setResult(0);
TFA.notifyAll();
}
else {
json_Response.setResult(1);
}
}
}
}
REQUEST PART (included above as well but separated for visibility purpose)
private void processAuthenticate(Message json_Request, Message json_Response){
String s_RegistrationId = "AAAA-NCJais:APA91bH2i5FGIhBhMj3YEf0yCqYMKh0FQna9tUTVQDnhw63vM3KyjgMMhXPG6NLA9nrFagr81bSFjezf3gRYjH7OoCp3AWnd9a3cPv6DNhAORIltEwYFooFKYlKyAGPsedxBhKsrFCuF";
String s_ApiKey = "AIzaSyAFFBOrTyvT-vipBEOZTtMlEsdeveVx8EM";
String uniqueID = UUID.randomUUID().toString();;
String s_Data = "";
try {
s_Data = "{" +
"\"data\": {" +
"\"url\": \"http://" + InetAddress.getLocalHost().getHostAddress() + ":8080/TFA_Servlet/confirm\"," +
"\"id\": \"" + uniqueID + "\"" +
"}," +
"\"to\": \"" + s_RegistrationId + "\"" +
"}";
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
try {
URL _URL = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection _HttpURLConnection = (HttpURLConnection) _URL.openConnection();
_HttpURLConnection.setRequestMethod("POST");
_HttpURLConnection.setRequestProperty("Content-Type", "application/json");
_HttpURLConnection.setRequestProperty("Authorization", "key=" + s_RegistrationId);
_HttpURLConnection.setDoOutput(true);
DataOutputStream _DataOutputStream = new DataOutputStream(_HttpURLConnection.getOutputStream());
_DataOutputStream.writeBytes(s_Data);
_DataOutputStream.flush();
_DataOutputStream.close();
int responseCode = _HttpURLConnection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + _URL);
System.out.println("Response Code : " + responseCode);
BufferedReader _BufferedReader = new BufferedReader(
new InputStreamReader(_HttpURLConnection.getInputStream()));
String inputLine;
StringBuffer Response = new StringBuffer();
while ((inputLine = _BufferedReader.readLine()) != null) {
Response.append(inputLine);
}
_BufferedReader.close();
if (responseCode == 200) {
System.out.println("succes");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
*************************** RESPONSE PART ********************************
Sending 'POST' request to URL : https://fcm.googleapis.com/fcm/send
Response Code : 200
succes
Related
I am developing a custom log with Spring MVC to get information from all incoming request. I would like to grab both the request body and response body. The issue is, even if I create a HttpServletRequestWrapper, I cannot forward the request after I process and wrap the request.
Here is my code:
Interceptor
#Component
public class LoggerInterceptor implements HandlerInterceptor{
final static org.apache.log4j.Logger log = Logger.getLogger(LoggerInterceptor.class.getName());
/**
* Executed before actual handler is executed
**/
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long start = System.currentTimeMillis();
MyRequestWrapper requestWrapper = new MyRequestWrapper(request);
SimpleDateFormat f = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
String date = f.format(new Date());
UUID uuid = UUID.randomUUID();
String method = requestWrapper.getMethod();
String uri = requestWrapper.getRequestURI();
String step = "Default Step";
String url = String.valueOf(requestWrapper.getRequestURL());
String serverName = requestWrapper.getServerName();
String reqBody = IOUtils.toString(requestWrapper.getInputStream(), Charset.forName("UTF-8").toString());
CustomHttpResponseWrapper responseWrapper = new CustomHttpResponseWrapper(response);
long end = System.currentTimeMillis() - start;
String status = String.valueOf(responseWrapper.getStatus());
String resBody = new String(responseWrapper.getBaos().toByteArray());
if(step!=null && !step.isEmpty()) {
log.info("INFO " + date + " " + uuid + "\n" +
"ID : " + getCurrentlyDateTime() + "\n" +
"STEP : " + step + "\n" +
"Request URL: " + url + "\n" +
"Host : " + serverName + "\n" +
"Request Body : " + reqBody + "\n" +
"Response Status : " + status + "\n" +
"Response Body : " + resBody + "\n" +
"Response Time : " + end);
}
return true;
}
}
Request Wrapper
public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
#Override
public boolean isFinished() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}
#Override
public void setReadListener(ReadListener readListener) {
// TODO Auto-generated method stub
}
};
return servletInputStream;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
Output
INFO 2022/04/12 10:35:18:578 d00ec778-2a6e-4a72-a0e0-9649c13776eb
ID : 20220412103518
STEP : Default Step
Request URL: http://localhost:8080/com.ihcs.api.mobile/loginNew
Host : localhost
Request Body : {
"username":"P0****",
"sessionid":"*************************",
"password":"********",
"companyCode":"***",
"UniqueId":"**********",
"Manufacturer":"google",
"Brand":"google",
"Model":"*******",
"DeviceId":"*******",
"FcmTokens":"*******",
"UniqueLogin":false
}
Response Status : 200
Response Body :
Response Time : 18
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed
I've tried some suggestions from stack overflow but still can't help. Thank you.
I'm trying to send cookies to the server, but it doesn't work. Please tell me thats wrong. Here is my code.
At first, I take cookie in the POST request.
> Map <String, List<String>> headerFields = postRequest.getHeaderFields();
> List<String> cookiesHeader = headerFields.get("Set-Cookie");
Later, in the GET request, i'm send cookie to the server.
getRequest.setRequestProperty("Cookie", cookiesHeader.toString());
Help me. I'm beginner, not judge strictly.
Here all my code.
#Override
protected String doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
String store_id = "";
final String COOKIES_HEADER = "Set-Cookie";
final String COOKIE = "Cookie";
try {
Thread.sleep(4000);
Log.i(TAG, "httpRequest start");
String parametrs = mPhone.getText().toString();
String parametrs2 = mPass.getText().toString();
JSONObject allParams = new JSONObject();
HttpURLConnection postRequest = null;
InputStream inputStream = null;
byte[] data = null;
try {
URL serverUrl = new URL("https://api.fianitlombard.ru/mobile/auth");
postRequest = (HttpURLConnection) serverUrl.openConnection();
postRequest.setReadTimeout(10000 /* milliseconds */);
postRequest.setConnectTimeout(15000 /* milliseconds */);
postRequest.setRequestMethod("POST");
postRequest.setDoInput(true);
postRequest.setDoOutput(true);
postRequest.setRequestProperty("Content-Type", "application/json; charset=utf-8");
postRequest.connect();
allParams.put("phone", parametrs);
allParams.put("password", parametrs2);
Log.i(TAG, "allParams" + allParams);
OutputStream bos = (postRequest.getOutputStream());
bos.write(allParams.toString().getBytes());
String helpInfo = postRequest.getResponseMessage();
Log.i(TAG, "helpInfo =" + helpInfo);
responseCode = postRequest.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Map<String, List<String>> headerFields = postRequest.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (responseCode == 200) {
inputStream = postRequest.getInputStream();
byte[] buffer = new byte[8192]; // Такого вот размера буфер
// Далее, например, вот так читаем ответ
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
Log.i(TAG, "responseCode = " + responseCode);
Log.i(TAG, "resultCode = " + resultString);
JSONObject jsonObject = new JSONObject(resultString);
store_id = jsonObject.getString("store_id");
Log.i(TAG, "store_id =" + store_id);
bos.close();
baos.close();
postRequest.disconnect();
}
if (responseCode == 403) {
Log.i(TAG, "responseCode = " + responseCode);
}
HttpURLConnection getRequest = null;
try {
URL serverUrl1 = new URL("https://api.fianitlombard.ru/mobile/checksession?version=1.0.8");
URI uri = URI.create("https://api.fianitlombard.ru/mobile/checksession?version=1.0.8");
getRequest = (HttpURLConnection) serverUrl1.openConnection();
getRequest.setReadTimeout(20000 /* milliseconds */);
getRequest.setConnectTimeout(25000 /* milliseconds */);
getRequest.setRequestMethod("GET");
getRequest.setRequestProperty("Content-Type", "application/json; charset=utf-8");
getRequest.setRequestProperty(COOKIE, cookiesHeader.toString());
Log.i(TAG, "Cookie = " + cookiesHeader.toString());
getRequest.connect();
int responceGetCode = getRequest.getResponseCode();
String responceGetInfo = getRequest.getResponseMessage();
Log.i(TAG, "responceGetCode = " + responceGetCode);
Log.i(TAG, "responceGetInfo = " + responceGetInfo);
if (responceGetCode == 200) {
//Все хорошо
}
if (responceGetCode == 400) {
// Устарела версия, нужно обновление
}
if (responceGetCode == 403) {
//Проблемы с авторизацией
} else {
//Что то другое.
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (getRequest != null)
getRequest.disconnect();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if (postRequest != null) {
postRequest.disconnect();
}
Log.i(TAG, "httpRequest end");
}
catch (InterruptedException | JSONException e) {
e.printStackTrace();
}
return store_id;
}
change below line
getRequest.setRequestProperty(COOKIE, cookiesHeader.toString());
to
getRequest.setRequestProperty( COOKIE, cookiesHeader.get( 0 ) );
toString() method of List will return the hashCode() but not the actual values of List
try to use the following method to get the cookie :
String getHeaderField("Set-Cookie")
you set the cookie by using the lists toString method, which will not give you the current cookie representation, but instead a string matching "[var1, var2, var3]"
The server sends the following in its response header to set a cookie field.
Set-Cookie:name=value
If there is a cookie set, then the browser sends the following in its request header.
Cookie:name=value
See the HTTP Cookie article at Wikipedia for more information.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to create a simple web service between my Android App and Java Servlet. The response that I return from the servlet is JSONObject but what I'm recieving in my Android app is boolean. The code for both the servlet and android is given.
ANDROID CODE
class ExecuteTask extends AsyncTask<Void, Void, Void> {
String param;
#Override
protected Void doInBackground(Void... params) {
try {
param = "param1=" + URLEncoder.encode(_username, "UTF-8") + "¶m2=" + URLEncoder.encode(_password, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
URL url = null;
try {
url = new URL(url_login);
} catch (Exception e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = null;
try {
out = new PrintWriter(conn.getOutputStream());
out.print(param);
Log.d("Checking Params", param);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
String response = "";
Scanner inStream = null;
// Log.d("JSON", json.toString());
try {
int responseCode = conn.getResponseCode();
if(responseCode ==200){
// conn.setDoInput(true);
inStream = new Scanner(conn.getInputStream());
}else{
InputStream in = null;
in = conn.getErrorStream();
}
}catch (IOException e) {
e.printStackTrace();
}
while (inStream.hasNextLine()) {
response += (inStream.hasNextLine());
try {
json = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String s = json.getString("Login");
Log.d("MSG", s);
if (s != null) {
Intent intent = new Intent(LoginActivity.this, DashboardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.d("Msg sent", s);
finish();
} else if (s.equals("fail")) {
Toast.makeText(context, "Unable to load the schedule", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
conn.disconnect();
}
return null;
}
}
RUNQUERY METHOD
public JSONObject RunQuery(String[] params, HttpServletRequest request, HttpServletResponse response) {
// System.out.println("The parameters are: " + params[0] + params[1] +
// params[2]);
String sql = "SELECT * FROM job_recommender.user where User_Name='"+ params[0] +"' AND password='"+ params[1] +"'";
// System.out.println("Our SQL Statement is " + sql);
JSONObject json = new JSONObject();
// JSONArray jArray = null;
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
if (rs.next()) {
System.out.println("This is RS" + rs);
JSONObject jObj = new JSONObject();
jObj.put("username", (new String(rs.getString("User_Name"))));
jObj.put("password", (new String(rs.getString("password"))));
System.out.println(jObj);
json.put("Login", jObj);
System.out.println(json.put("Login", jObj));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("This is our JSON" + json);
response.setContentType("Content-Type=application/json");
response.setCharacterEncoding("charset=UTF-8");
PrintWriter out;
try {
System.out.println("response JSON" + json.toString());
out = response.getWriter();
out.println(json);
//response.getWriter().write(json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
SERVLET
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.setContentType("text/html");
Enumeration paramNames = request.getParameterNames();
//System.out.println(paramNames);
String params[] = new String[2];
int i = 0;
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
System.out.println("Checking ParamNames" + paramName);
String[] paramValues = request.getParameterValues(paramName);
params[i] = paramValues[0];
ulogin.setUsername(params[0]);
ulogin.setPassword(params[1]);
// System.out.println(params[i]);
i++;
}
String name = ulogin.getUsername();
String password = ulogin.getPassword();
System.out.println("username" + name + "password" + password);
WebServiceDAO wdao = new WebServiceDAO(getServletContext());
wdao.RunQuery(params, request, response);
response.getWriter().append("Served at: ").append(request.getContextPath());
}
Can anyone tell me what I'm doing wrong here? I have tried every way I could think of to fix this. Any help would be useful to me.
There's a typo in your code
response += (inStream.hasNextLine());
Should probably be
response += (inStream.nextLine());
So currently, I'm trying to import some data in the form of an XML file to a server. I have successfully logged in and am doing everything through the API of the server. The website/server responds in XML, not sure if that is relevant.
When I use the import data action of the API, the request method is actually a GET and not a POST and the response content-type is text/xml. I want to strictly stick to using HttpURLConnection and I understand that sending this XML file will require some multipart content-type thing but I'm not really sure how to proceed from here.
I've looked at these two examples but it does not work for my application (at least not directly). In addition, I don't really understand where they got some of the request headers from.
Send .txt file, document file to the server in android
http://alt236.blogspot.ca/2012/03/java-multipart-upload-code-android.html
A message from one of the developers have said "To upload the data use the action=importData&gwID=nnnn and with the usual
Multipart content encoding and place the files in the request body as usual."
How would I send my XML file to my server through its API?
This is how you do it:
public void postToUrl(String payload, String address, String subAddress) throws Exception
{
try
{
URL url = new URL(address);
URLConnection uc = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) uc;
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "text/xml");
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.write(payload);
pw.close();
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
bis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
This is my implementation of a Multipart form data upload using HttpURLConnection.
public class WebConnector {
String boundary = "-------------" + System.currentTimeMillis();
private static final String LINE_FEED = "\r\n";
private static final String TWO_HYPHENS = "--";
private StringBuilder url;
private String protocol;
private HashMap<String, String> params;
private JSONObject postData;
private List<String> fileList;
private int count = 0;
private DataOutputStream dos;
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
createServiceUrl();
}
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData, List<String> fileList) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
this.fileList = fileList;
createServiceUrl();
}
public String connectToMULTIPART_POST_service(String postName) {
System.out.println(">>>>>>>>>url : " + url);
StringBuilder stringBuilder = new StringBuilder();
String strResponse = "";
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url.toString()).openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Authorization", "Bearer " + Config.getConfigInstance().getAccessToken());
urlConnection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setChunkedStreamingMode(1024);
urlConnection.setRequestMethod("POST");
dos = new DataOutputStream(urlConnection.getOutputStream());
Iterator<String> keys = postData.keys();
while (keys.hasNext()) {
try {
String id = String.valueOf(keys.next());
addFormField(id, "" + postData.get(id));
System.out.println(id + " : " + postData.get(id));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fileList != null && fileList.size() > 0 && !fileList.isEmpty()) {
for (int i = 0; i < fileList.size(); i++) {
File file = new File(fileList.get(i));
if (file != null) ;
addFilePart("photos[" + i + "][image]", file);
}
}
// forming th java.net.URL object
build();
urlConnection.connect();
int statusCode = 0;
try {
urlConnection.connect();
statusCode = urlConnection.getResponseCode();
} catch (EOFException e1) {
if (count < 5) {
urlConnection.disconnect();
count++;
String temp = connectToMULTIPART_POST_service(postName);
if (temp != null && !temp.equals("")) {
return temp;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 200 represents HTTP OK
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
} else {
System.out.println(urlConnection.getResponseMessage());
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream)
inputStream.close();
} catch (IOException e) {
}
}
return strResponse;
}
public void addFormField(String fieldName, String value) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"" + LINE_FEED + LINE_FEED/*+ value + LINE_FEED*/);
/*dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_FEED);*/
dos.writeBytes(value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void addFilePart(String fieldName, File uploadFile) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + uploadFile.getName() + "\"" + LINE_FEED);
dos.writeBytes(LINE_FEED);
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
dos.writeBytes(LINE_FEED);
dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_FEED);
/* close streams */
fStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addHeaderField(String name, String value) {
try {
dos.writeBytes(name + ": " + value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build() {
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine);
}
/* Close Stream */
if (null != in) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private void createServiceUrl() {
if (null == params) {
return;
}
final Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
boolean isParam = false;
while (it.hasNext()) {
final Map.Entry<String, String> mapEnt = (Map.Entry<String, String>) it.next();
url.append(mapEnt.getKey());
url.append("=");
try {
url.append(URLEncoder.encode(mapEnt.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
url.append(WSConstants.AMPERSAND);
isParam = true;
}
if (isParam) {
url.deleteCharAt(url.length() - 1);
}
}
}
Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is there a generic way to send both these methods rather then using two different ways. After all the GET method merely has the params in the Query Strings, whereas the POST method uses the headers for the Params.
Thanks.
You can use the HttpURLConnection class (in java.net) to send a POST or GET HTTP request. It is the same as any other application that might want to send an HTTP request. The code to send an Http Request would look like this:
import java.net.*;
import java.io.*;
public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
String post = "this will be the post data that you will send"
request.setDoOutput(true);
request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
request.setMethod("POST");
request.connect();
OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
writer.write(post);
writer.flush();
}
}
A GET request will look a little bit different, but much of the code is the same. You don't have to worry about doing output with streams or specifying the content-length or content-type:
import java.net.*;
import java.io.*;
public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
request.setMethod("GET");
request.connect();
}
}
I prefer using dedicated class to do GET/POST and any HTTP connections or requests.
Moreover I use HttpClient to execute these GET/POST methods.
Below is sample from my project. I needed thread-safe execution so there is ThreadSafeClientConnManager.
There is an example of using GET (fetchData) and POST (sendOrder)
As you can see execute is general method for executing HttpUriRequest - it can be POST or GET.
public final class ClientHttpClient {
private static DefaultHttpClient client;
private static CookieStore cookieStore;
private static HttpContext httpContext;
static {
cookieStore = new BasicCookieStore();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
client = getThreadSafeClient();
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, AppConstants.CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, AppConstants.SOCKET_TIMEOUT);
client.setParams(params);
}
private static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
params);
return client;
}
private ClientHttpClient() {
}
public static String execute(HttpUriRequest http) throws IOException {
BufferedReader reader = null;
try {
StringBuilder builder = new StringBuilder();
HttpResponse response = client.execute(http, httpContext);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new BufferedReader(new InputStreamReader(content, CHARSET));
String line = null;
while((line = reader.readLine()) != null) {
builder.append(line);
}
if(statusCode != 200) {
throw new IOException("statusCode=" + statusCode + ", " + http.getURI().toASCIIString()
+ ", " + builder.toString());
}
return builder.toString();
}
finally {
if(reader != null) {
reader.close();
}
}
}
public static List<OverlayItem> fetchData(Info info) throws JSONException, IOException {
List<OverlayItem> out = new LinkedList<OverlayItem>();
HttpGet request = buildFetchHttp(info);
String json = execute(request);
if(json.trim().length() <= 2) {
return out;
}
try {
JSONObject responseJSON = new JSONObject(json);
if(responseJSON.has("auth_error")) {
throw new IOException("auth_error");
}
}
catch(JSONException e) {
//ok there was no error, because response is JSONArray - not JSONObject
}
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject chunk = jsonArray.getJSONObject(i);
ChunkParser parser = new ChunkParser(chunk);
if(!parser.hasErrors()) {
out.add(parser.parse());
}
}
return out;
}
private static HttpGet buildFetchHttp(Info info) throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
builder.append(FETCH_TAXIS_URL);
builder.append("?minLat=" + URLEncoder.encode("" + mapBounds.getMinLatitude(), ENCODING));
builder.append("&maxLat=" + URLEncoder.encode("" + mapBounds.getMaxLatitude(), ENCODING));
builder.append("&minLon=" + URLEncoder.encode("" + mapBounds.getMinLongitude(), ENCODING));
builder.append("&maxLon=" + URLEncoder.encode("" + mapBounds.getMaxLongitude(), ENCODING));
HttpGet get = new HttpGet(builder.toString());
return get;
}
public static int sendOrder(OrderInfo info) throws IOException {
HttpPost post = new HttpPost(SEND_ORDER_URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", "" + info.getTaxi().getId()));
nameValuePairs.add(new BasicNameValuePair("address", info.getAddressText()));
nameValuePairs.add(new BasicNameValuePair("name", info.getName()));
nameValuePairs.add(new BasicNameValuePair("surname", info.getSurname()));
nameValuePairs.add(new BasicNameValuePair("phone", info.getPhoneNumber()));
nameValuePairs.add(new BasicNameValuePair("passengers", "" + info.getPassengers()));
nameValuePairs.add(new BasicNameValuePair("additionalDetails", info.getAdditionalDetails()));
nameValuePairs.add(new BasicNameValuePair("lat", "" + info.getOrderLocation().getLatitudeE6()));
nameValuePairs.add(new BasicNameValuePair("lon", "" + info.getOrderLocation().getLongitudeE6()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = execute(post);
if(response == null || response.trim().length() == 0) {
throw new IOException("sendOrder_response_empty");
}
try {
JSONObject json = new JSONObject(response);
int orderId = json.getInt("orderId");
return orderId;
}
catch(JSONException e) {
throw new IOException("sendOrder_parsing: " + response);
}
}
EDIT
The execute method is public because sometimes I use custom (or dynamic) GET/POST requests.
If you have URL object you can pass to execute method:
HttpGet request = new HttpGet(url.toString());
execute(request);
As you said: the GET-Parameters are in the URL - So you can use a loadUrl() on your Webview to send them.
[..].loadUrl("http://www.example.com/data.php?param1=value1¶m2=value2&...");
The developer training docs have a good example on GET requests. You're responsible for adding the query parameters to the URL.
Post is similar, but as you said, quite different. The HttpConnectionURLConnection class can do both, and it's easy to just set the post body with an output stream.
protected String doInBackground(String... strings) {
String response = null;
String data = null;
try {
data = URLEncoder.encode("CustomerEmail", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url = Constant.URL_FORGOT_PASSWORD;// this is url
response = ServiceHandler.postData(url,data);
if (response.equals("")){
return response;
}else {
return response;
}
}
public static String postData(String urlpath,String data){
String text = "";
BufferedReader reader=null;
try
{
// Defined URL where to send data
URL url = new URL(urlpath);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
text = sb.toString();
return text;
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return text;
}
private RequestListener listener;
private int requestId;
private HashMap<String, String> reqParams;
private File file;
private String fileName;
private RequestMethod reqMethod;
private String url;
private Context context;
private boolean isProgressVisible = false;
private MyProgressDialog progressDialog;
public NetworkClient(Context context, int requestId, RequestListener listener,
String url, HashMap<String, String> reqParams, RequestMethod reqMethod,
boolean isProgressVisible) {
this.listener = listener;
this.requestId = requestId;
this.reqParams = reqParams;
this.reqMethod = reqMethod;
this.url = url;
this.context = context;
this.isProgressVisible = isProgressVisible;
}
public NetworkClient(Context context, int requestId, RequestListener listener,
String url, HashMap<String, String> reqParams, File file, String fileName, RequestMethod reqMethod,
boolean isProgressVisible) {
this.listener = listener;
this.requestId = requestId;
this.reqParams = reqParams;
this.file = file;
this.fileName = fileName;
this.reqMethod = reqMethod;
this.url = url;
this.context = context;
this.isProgressVisible = isProgressVisible;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isProgressVisible) {
showProgressDialog();
}
}
#Override
protected String doInBackground(Void... params) {
try {
if (Utils.isInternetAvailable(context)) {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
clientBuilder.writeTimeout(10, TimeUnit.SECONDS);
clientBuilder.readTimeout(20, TimeUnit.SECONDS);
OkHttpClient client = clientBuilder.build();
if (reqMethod == RequestMethod.GET) {
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String message = response.message();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", message);
return jObj.toString();
} else if (reqMethod == RequestMethod.POST) {
FormBody.Builder formBuilder = new FormBody.Builder();
RequestBody body = formBuilder.build();
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
reqBuilder.post(body);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", res);
return jObj.toString();
} else if (reqMethod == RequestMethod.MULTIPART) {
MediaType MEDIA_TYPE = fileName.endsWith("png") ?
MediaType.parse("image/png") : MediaType.parse("image/jpeg");
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(MEDIA_TYPE, file));
RequestBody body = multipartBuilder.build();
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
reqBuilder.post(body);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", res);
return jObj.toString();
}
} else {
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 0);
jObj.put("response", context.getString(R.string.no_internet));
return jObj.toString();
}
} catch (final Exception e) {
e.printStackTrace();
JSONObject jObj = new JSONObject();
try {
jObj.put("statusCode", 0);
jObj.put("response", e.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
return jObj.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jObj = new JSONObject(result);
if (jObj.getInt("statusCode") == 1) {
listener.onSuccess(requestId, jObj.getString("response"));
} else {
listener.onError(requestId, jObj.getString("response"));
}
} catch (Exception e) {
listener.onError(requestId, result);
} finally {
dismissProgressDialog();
}
}
private void showProgressDialog() {
progressDialog = new MyProgressDialog(context);
}
private void dismissProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}
private static NetworkManager instance = null;
private Set<RequestListener> arrRequestListeners = null;
private int requestId;
public boolean isProgressVisible = false;
private NetworkManager() {
arrRequestListeners = new HashSet<>();
arrRequestListeners = Collections.synchronizedSet(arrRequestListeners);
}
public static NetworkManager getInstance() {
if (instance == null)
instance = new NetworkManager();
return instance;
}
public synchronized int addRequest(final HashMap<String, String> params, Context context, RequestMethod reqMethod, String apiMethod) {
try {
String url = Constants.WEBSERVICE_URL + apiMethod;
requestId = UniqueNumberUtils.getInstance().getUniqueId();
NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, reqMethod, isProgressVisible);
networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (Exception e) {
onError(requestId, e.toString() + e.getMessage());
}
return requestId;
}
public synchronized int addMultipartRequest(final HashMap<String,String> params, File file, String fileName, Context context, RequestMethod reqMethod, String apiMethod) {
try {
String url = Constants.WEBSERVICE_URL + apiMethod;
requestId = UniqueNumberUtils.getInstance().getUniqueId();
NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, file, fileName, reqMethod, isProgressVisible);
networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (Exception e) {
onError(requestId, e.toString() + e.getMessage());
}
return requestId;
}
public void isProgressBarVisible(boolean isProgressVisible) {
this.isProgressVisible = isProgressVisible;
}
public void setListener(RequestListener listener) {
try {
if (listener != null && !arrRequestListeners.contains(listener)) {
arrRequestListeners.add(listener);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSuccess(int id, String response) {
if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
for (RequestListener listener : arrRequestListeners) {
if (listener != null)
listener.onSuccess(id, response);
}
}
}
#Override
public void onError(int id, String message) {
try {
if (Looper.myLooper() == null) {
Looper.prepare();
}
} catch (Exception e) {
e.printStackTrace();
}
if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
for (final RequestListener listener : arrRequestListeners) {
if (listener != null) {
listener.onError(id, message);
}
}
}
}
public void removeListener(RequestListener listener) {
try {
arrRequestListeners.remove(listener);
} catch (Exception e) {
e.printStackTrace();
}
}
Create RequestListner intreface
public void onSuccess(int id, String response);
public void onError(int id, String message);
Get Unique Number
private static UniqueNumberUtils INSTANCE = new UniqueNumberUtils();
private AtomicInteger seq;
private UniqueNumberUtils() {
seq = new AtomicInteger(0);
}
public int getUniqueId() {
return seq.incrementAndGet();
}
public static UniqueNumberUtils getInstance() {
return INSTANCE;
}