I'm trying to post a comment from desktop application to Trac.
I'm using apache http client library in this project here is a link
Here is my code, sorry if it's hard to read
public class TestComment {
private static String cookie;
public static void main(String[] args) throws Exception {
CookieHandler.setDefault(new CookieManager());
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:8080/mytrac/login");
BasicHeader authHeader = new BasicHeader("Authorization", "Basic " + encodedPassword("admin", "123123"));
httpGet.addHeader(authHeader);
HttpResponse response = defaultHttpClient.execute(httpGet);
List<Cookie> cookies = defaultHttpClient.getCookieStore().getCookies();
String token = null;
if(!cookies.isEmpty()){
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
token = cookies.get(i).toString().substring(43, 67);
System.out.println(token);
}
}
setCookie(token);
responseLog(response);
HttpPost httpPost = new HttpPost("http://localhost:8080/mytrac/ticket/2#comment:5");
httpPost.setHeader(authHeader);
httpPost.setHeader("Host", "localhost:8080");
httpPost.setHeader("User-Agent", "Mozilla/5.0");
httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Accept-Language", "en-US,en;q=0.8");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Referer", "http://localhost:8080/mytrac/ticket/2");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("__FORM_TOKEN", token));
formparams.add(new BasicNameValuePair("comment", "Test comment"));
formparams.add(new BasicNameValuePair("field_reporter", "admin"));
httpPost.setEntity(new UrlEncodedFormEntity(formparams));
response = defaultHttpClient.execute(httpPost);
responseLog(response);
System.out.println(response.getStatusLine());
}
private static String encodedPassword(String username, String password) {
byte[] encodedPassword = (username + ":" + password).getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(encodedPassword);
}
private static void responseLog(org.apache.http.HttpResponse httpResponse) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse. getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer();
String line1;
while ((line1 = bufferedReader.readLine()) != null) {
stringBuffer.append(line1 + "\n");
}
System.out.println(stringBuffer) ;
}
public static String getCookie() {
cookie = cookie.substring(cookie.indexOf(":") + 1);
return cookie;
}
public static void setCookie(String cookie) {
TestComment.cookie = cookie;
}
}
When I run this code I get 200 code it tells ok and I even get my comment in Text-Aria form, but don't post it. When I post a comment in browser the code is 303. Where am I wrong, may be I am on totaly wrong way?
We resolved the problem
I didn't know but i just needed to send one more form, we need to get view time from trac and send it as a form:
formparams.add(new BasicNameValuePair("view_time", view_time));
now it works
Related
I try to connect to the poloniex.com API https://poloniex.com/support/api/ which says:
(All calls to the trading API are sent via HTTP POST to https://poloniex.com/tradingApi and must contain the following headers:
Key - Your API key.
Sign - The query's POST data signed by your key's "secret" according to the HMAC-SHA512 method.
Additionally, all queries must include a "nonce" POST parameter. The nonce parameter is an integer which must always be greater than the previous nonce used.)
But I always get
{"error":"Invalid
API key\/secret pair."}
My hmac512Digest works fine, I've checked it.
There must be something wrong in my code.
Can someone please Help?
public class Pol2 {
public static String POLONIEX_SECRET_KEY = "12345";
public static String POLONIEX_API_KEY = "ABX";
public static void main(String[] args) {
try {
accessPoloniex();
} catch (IOException e) {
e.printStackTrace();
}
}
public static final void accessPoloniex() throws IOException {
final String nonce = String.valueOf(System.currentTimeMillis());
String connectionString = "https://poloniex.com/tradingApi";
String queryArgs = "command=returnBalances";
String hmac512 = hmac512Digest(queryArgs, POLONIEX_SECRET_KEY);
// Produce the output
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.append(queryArgs);
writer.flush();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(connectionString);
post.addHeader("Key", POLONIEX_API_KEY); //or setHeader?
post.addHeader("Sign", hmac512); //or setHeader?
post.setEntity(new ByteArrayEntity(out.toByteArray()));
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("command", "returnBalances"));
params.add(new BasicNameValuePair("nonce", nonce));
CloseableHttpResponse response = null;
Scanner in = null;
try {
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext()) {
System.out.println(in.next());
}
EntityUtils.consume(entity);
} finally {
in.close();
response.close();
}
}
}
I struggled with this myself and finally got it to work. Here's a very basic, working example:
public class PoloTest {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, ClientProtocolException, IOException {
String key = "YOUR API KEY HERE";
String secret = "YOUR API SECRET HERE";
String url = "https://poloniex.com/tradingApi";
String nonce = String.valueOf(System.currentTimeMillis());
String queryArgs = "command=returnBalances&nonce=" + nonce;
Mac shaMac = Mac.getInstance("HmacSHA512");
SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA512");
shaMac.init(keySpec);
final byte[] macData = shaMac.doFinal(queryArgs.getBytes());
String sign = Hex.encodeHexString(macData);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.addHeader("Key", key);
post.addHeader("Sign", sign);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("command", "returnBalances"));
params.add(new BasicNameValuePair("nonce", nonce));
post.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity responseEntity = response.getEntity();
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(responseEntity));
}
}
I've looked into the Python example that they've linked to on their page. The nonce parameter must be MAC'ed along with the command and the final MAC is appended in Hex-encoded format:
String queryArgs = "command=returnBalances&nonce=" + nonce;
String hmac512 = hmac512Digest(queryArgs, POLONIEX_SECRET_KEY);
Also, the following
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.append(queryArgs);
writer.flush();
//...
post.setEntity(new ByteArrayEntity(out.toByteArray()));
can be reduced to
post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
The nonce parameter must be MAC'ed along with the command...
If a hash is a one way function, and Polo have no idea what nonce I might choose, (or when, if i'm using UTC), how can Polo ever extract anything meaningful from what I send them.
how can i call http post requst with multiple parameter.
like this
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
webClient.UploadStringAsync(new Uri(URL), "POST", JSON);
this one in c#. but i want in android
i have already try this
public String postServiceCall(String paraURL,JSONArray jsonParams, String usrId, String syncDt){
TAG = "makeHttpRequestJSONObject";
Log.d(MODULE, TAG + " called");
String json = "";
InputStream is = null;
try{
HttpParams httpParams = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
String params = "UserId="+ usrId +"&SyncDate="+syncDt;
String encodedUrl = URLEncoder.encode (params,"UTF-8");
HttpPost httpPost = new HttpPost(paraURL+encodedUrl);
httpPost.setHeader( "Content-Type", "application/json" );
Log.v(MODULE, TAG + ", POST paraURL " + (paraURL+encodedUrl));
Log.v(MODULE, TAG + ", POST paraURL jsonParams.toString() " + (jsonParams.toString()));
httpPost.setEntity(new ByteArrayEntity(jsonParams.toString().getBytes("UTF8")));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString().trim();
json = json.substring(1,3);
Log.v(MODULE, TAG + ", json data " + json);
} catch (Exception e){
Log.e(MODULE, TAG + "Exception Occurs " + e);
json = "";
}
return json;
}
}
this code not work properly. this code post only the json. here userid and syncdate not send to server side
please check this
String encodedUrl = URLEncoder.encode (params,"UTF-8");
example
your code returns the url like this
input "http://test.com/ttttt?query=jjjj test"
output "http://test.com/ttttt?query=jjjj+test"
but your need url like this
output "http://test.com/ttttt?query=jjjj%20test"
so you can try this function for url encoding
public String parseUrl(String surl) throws Exception
{
URL u = new URL(surl);
return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}
OR
This may help you to comfortable with higher versions
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
I've been trying to get this work for a while now. Im working on an app where the user signs in with a username and password which uses a httppost request to post to the server. i get the correct response, and during the post i store the session cookie that the server gives me. (I store it in a cookie store)
But when i try to click a link on the menu ( which does a second http post) after i logged in, the servers gives me a message saying that i am not logged in. But i send the cookie that i recieved in the first post to the server in the second post, yet the server does not recognize that i am logged in. To test this more easily i used the chrome plug in "Postman" which lets you post to websites easily. The only time it worked was when i log in to the website using chrome then use Postman to do the second post, which successfully gives me a response. however, when i use Postman to log in, then also use postman to attempt the second post , again, "Not logged in". Im guessing that the cookie is not being stored properly in the app. How could i go about fixing this? I read some stuff about storing the cookies in something called "Shared Preferences", is that possibly a fix? If so, what is it and how could i store the cookies there?
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
LoginLayout.httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
CookieStore cookiestore = LoginLayout.httpClient.getCookieStore();
HttpResponse response = LoginLayout.httpClient.execute(request);
List<Cookie> cookies = LoginLayout.httpClient.getCookieStore().getCookies();
cookiestore.addCookie(cookie);
cookie = cookies.get(0);
cookieValue = "ASPSESSIONIDCQTCRACT=" + cookiestore.getCookies();
System.out.println("The cookie" + cookieValue);
List<Cookie> cookiess = cookiestore.getCookies();
cookiee = cookies.get(0);
Header[] headers = response.getAllHeaders();
System.out.println("length" + headers.length);
for (int i=0; i < headers.length; i++) {
Header h = headers[i];
System.out.println( "Header names: "+h.getName());
System.out.println( "Header Value: "+h.getValue());
}
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
// System.out.println( mCookie);
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
Here is the getter so i can access the cookie from the cookie store in the next activity
public static String getCookie(){
return cookiee.getName() +"="+cookiee.getValue();
}
Here is the second post where i try to retrieve the stored cookie, which it seems to do sucessfully, however the server doesnt recognize i am logged in
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpPost request = new HttpPost(url);
request.setHeader("Cookie", LoginLayout.getCookie());
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = LoginLayout.httpClient.execute(request);
Header[] headers = response.getAllHeaders();
System.out.println("length" + headers.length);
for (int i=0; i < headers.length; i++) {
Header h = headers[i];
System.out.println( "Header names: "+h.getName());
System.out.println( "Header Value: "+h.getValue());
}
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
//System.out.println( mCookie);
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You have to make sure that your HttpClient is using the same HttpContext on each request.
The CookieStore is associated with the HttpContext so create a new instance of HttpContext will create a new CookieStore as well.
The best way I found is to create a static instance of HttpContext and use it on every request.
Below I added an part of a class I'm using in my apps:
public class ApiClient {
// Constants
private final static String TAG = "ApiClient";
private final static String API_URL = "your-url";
// Data
private static ApiClient mInstance;
private HttpClient mHttpClient;
private ThreadSafeClientConnManager mConnectionManager;
private HttpPost mPost;
/*
* we need it static because otherwise it will be recreated and the session
* will be lost
*/
private static HttpContext mHttpContext;
private HttpParams mParams;
private Context mContext;
public ApiClient(Context pContext) {
mParams = new BasicHttpParams();
mContext = pContext;
if (null == mHttpContext) {
CookieStore cookieStore = new BasicCookieStore();
mHttpContext = new BasicHttpContext();
mHttpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}
ConnManagerParams.setMaxTotalConnections(mParams, 300);
HttpProtocolParams.setVersion(mParams, HttpVersion.HTTP_1_1);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
mConnectionManager = new ThreadSafeClientConnManager(mParams, schemeRegistry);
mHttpClient = new DefaultHttpClient(mConnectionManager, mParams);
}
public static ApiClient getInstance(Context pContext) {
if (null == mInstance) {
return (mInstance = new ApiClient(pContext));
} else {
return mInstance;
}
}
public void testPOST() {
List<NameValuePair> requestParams = new ArrayList<NameValuePair>();
requestParams.add(new BasicNameValuePair("param1", "value1"));
requestParams.add(new BasicNameValuePair("param2", "value2"));
mPost = new HttpPost(API_URL);
try {
mPost.setEntity(new UrlEncodedFormEntity(requestParams, HTTP.UTF_8));
HttpResponse responsePOST = mHttpClient.execute(mPost, mHttpContext);
HttpEntity resEntity = responsePOST.getEntity();
String result = EntityUtils.toString(resEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
To test it try setting the correct API_URL and
ApiClient api = ApiClient.getInstance(somContext);
api.testPOST();
I'm having this issue and I need to put or patch data to the server. I know how to do a standard post, but how can I do this PATCH or PUT to the server?
The URL to the server is PATCH to www.example.com/api/documents and parameter is doc_id(integer).
This is what I currently have
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("content-type", "application/json");
httpPost.setHeader("accept-charset", "utf8");
try {
HttpResponse response = httpClient.execute(httpPost);
responseString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("Request exception:", "excpetion", e);
}
return responseString;
But this code I think is wrong as hell :)
This is the most common way---
Creating jsonObj and putting json values:
JSONObject jsonObj = new JSONObject();
jsonObj .put("doc_id", <put your value> + "");
String response = callPutService(source, password, callingAPI, jsonObj);
This is the callPutService that is called:
public String callPutService(String userName, String password,
String type, JSONObject jsonObject) {
String line = null, jsonString = "";
HttpResponse response = null;
InputStream inputStream = null;
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.
setConnectionTimeout
(client.getParams(), 20000); // Timeout Limit
HttpPut put = new HttpPut(WEBSERVICE + type);
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
put.setHeader("Authorization",
"basic " + Base64.
encodeToString((userName + ":" + password).getBytes(),
Base64.URL_SAFE | Base64.NO_WRAP));
put.setEntity(se);
response = client.execute(put);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode == 200){
//do whatever
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonString;
}
I am trying to hit some URL using Post Method from client side with some data in the format of "NameValuePair", And receive that data from URL in servlet (server side) for performing some calculation and send back response to the client in JSON fromat.
But I am able to find correct data on Servlet (server)
Hit URL from Client Side
private void sendHTTPSPost() throws Exception {
String url = "http://localhost:8080/test/Registration";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("name", "A"));
urlParameters.add(new BasicNameValuePair("age", "12"));
urlParameters.add(new BasicNameValuePair("sex", "M"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
On Servlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
System.out.println("Value of param is ------------------"+paramName);
String paramValue = request.getHeader(paramName);
System.out.println("Value of key is ------------------"+paramValue);
}
}
I tried a lot but not get correct result.
you are missing
post.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
You are getting the headers from the request you must use the request.getParameterNames() to get the parameters.
You can use -
requests.getParameter("name"); //returns A
requests.getParameter("age"); //returns 12
requests.getParameter("sex"); //returns M