Написать на Java API соеденение по примеру PHP
хочу по апи на java получить .csv файл для дальнейшей обработки, пример есть только на PHP, несколько дней уже пробую по разному и никак не могу получить в ответ этот файл, насколько понимаю, я не правильно отправляю туда запрос, вернее не в том формате шифровки в котором требуется. Знаний у меня мало, опыта тем более, укажите плиз направление в котором копать?
Описание к примеру -- При формировании контрольной подписи значения полей "склеиваются" в одну строку с разделителем "+" в следующем порядке: anonymous dtmfUserAnswer firstTime from fromNumber names numbersInvolved numbersRinged outgoingLine state to toAnswer toNumber tree showTreeId type user секретный ключ. От полученной строки вычисляется MD5.
Пример на PHP
$user = '081121';
$from = date('d.m.Y');
$to = date('d.m.Y');
$type = '0';
$state = '0';
$tree = '';
$showTreeId = '1';
$fromNumber = '';
$numbersRinged = 0;
$numbersInvolved = 0;
$names = 0;
$outgoingLine = 1;
$toNumber = '';
$toAnswer = '';
$anonymous = '1';
$firstTime = '0';
$dtmfUserAnswer = 0;
$secret = 'ваш ключ интеграции';
$hashString = join('+', array($anonymous, $dtmfUserAnswer, $firstTime, $from, $fromNumber, $names, $numbersInvolved, $numbersRinged, $outgoingLine, $showTreeId, $state, $to, $toAnswer, $toNumber, $tree, $type, $user, $secret));
$hash = md5($hashString);
$url = 'https://someurl.com/api/statistic/export';
$query = http_build_query(array(
'anonymous' => $anonymous,
'firstTime' => $firstTime,
'from' => $from,
'fromNumber' => $fromNumber,
'numbersRinged' => $numbersRinged
'outgoingLine' => $outgoingLine,
'showTreeId' => $showTreeId,
'state' => $state,
'to' => $to,
'toAnswer' => $toAnswer,
'toNumber' => $toNumber,
'tree' => $tree,
'type' => $type,
'user' => $user,
'dtmfUserAnswer' => $dtmfUserAnswer,
'hash' => $hash,
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
header("Content-Disposition: attachment; filename=stat_$from-$to.csv");
echo $output;
Мой код если нужно но он так и не работает)
String urlAdress = "https://someurl.com/api/statistic/export";
URL url;
HttpURLConnection httpURLConnection;
OutputStream os = null;
InputStreamReader isR = null;
BufferedReader bfR = null;
StringBuilder stringBuilder = new StringBuilder();
try{
Map<String,String> postargs = new HashMap<>();
postargs.put("anonymous", "1");
postargs.put("firstTime", "0");
postargs.put("from", "27.04.2022");
postargs.put("fromNumber", "");
postargs.put("state", "0");
postargs.put("to", "27.04.2022");
postargs.put("toAnswer", "");
postargs.put("toNumber", "");
postargs.put("tree", "");
postargs.put("type", "0");
postargs.put("user", "081121");
postargs.put("secret", "XXXXXXXXXXXXXXX");
byte[] out = postargs.toString().getBytes();
url = new URL(urlAdress);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.addRequestProperty("User-Agent", "Mozilla/5.0");
httpURLConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setConnectTimeout(200);
httpURLConnection.setReadTimeout(200);
httpURLConnection.connect();
try {
os = httpURLConnection.getOutputStream();
os.write(out);
}catch (Exception e){
System.err.print(e.getMessage());
}
System.out.println(httpURLConnection.getResponseCode());
if (HttpURLConnection.HTTP_OK == httpURLConnection.getResponseCode()){
isR = new InputStreamReader(httpURLConnection.getInputStream());
bfR = new BufferedReader(isR);
String line;
while ((line=bfR.readLine()) != null){
stringBuilder.append(line);
System.out.println(line);
}
}
System.out.println(isR);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
System.err.print(e.getMessage());
}finally {
try{
isR.close();
}catch (IOException e){
//e.printStackTrace();
}
try{
bfR.close();
}catch (IOException e){
e.printStackTrace();
}
try{
os.close();
}catch (IOException e){
e.printStackTrace();
}
}
Ответы (2 шт):
Это все очень далеко от того, что делает PHP
Для того, чтобы отправить http запрос, лучше использовать что-то более высокоуровневое, к примеру, я взял okhttp, подключайте зависимость:
https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/4.9.3
Поскольку я не знаю секретного ключа, то пртестировать это не могу, однако, примерно это будет выглядеть так (дальше разбирайтесь и дебажте):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.xml.bind.DatatypeConverter;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Test {
public static void main(String[] args) throws Exception {
Map<String, String> postargs = new LinkedHashMap<>();
postargs.put("anonymous", "1");
postargs.put("dtmfUserAnswer", "0");
postargs.put("firstTime", "0");
postargs.put("from", "27.04.2022");
postargs.put("fromNumber", "");
postargs.put("names", "0");
postargs.put("numbersInvolved", "0");
postargs.put("numbersRinged", "0");
postargs.put("outgoingLine", "1");
postargs.put("showTreeId", "1");
postargs.put("state", "0");
postargs.put("to", "27.04.2022");
postargs.put("toAnswer", "");
postargs.put("toNumber", "");
postargs.put("tree", "");
postargs.put("type", "0");
postargs.put("user", "081121");
String secret = "secret";
String urlAdress = "https://someurl.com/api/statistic/export";
Map<String, String> postargsWithMd5 = addMd5(secret, postargs);
String content = send(urlAdress, postargsWithMd5);
System.out.println(content);
}
private static Map<String, String> addMd5(String secret, Map<String, String> postargs) throws NoSuchAlgorithmException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : postargs.entrySet()) sb.append(entry.getValue()).append("+");
String hashString = sb.append(secret).toString();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(hashString.getBytes());
postargs.put("hash", DatatypeConverter.printHexBinary(md.digest()));
return postargs;
}
private static String send(String url, Map<String, String> postargs) throws IOException {
FormBody.Builder bodyBuilder = new FormBody.Builder();
for (Map.Entry<String, String> entry : postargs.entrySet()) bodyBuilder.add(entry.getKey(), entry.getValue());
Request request = new Request.Builder()
.addHeader("Content-Disposition", String.join("", "attachment; filename=stat_", postargs.get("from"), "-" + postargs.get("to"), ".csv"))
.url(url)
.post(bodyBuilder.build())
.build();
Response response = new OkHttpClient().newCall(request).execute();
return new BufferedReader(new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8))
.lines().collect(Collectors.joining("\n"));
}
}
Для отправка http запрос, вы можете использовать мою библиотеку. Итак, охраняйте это код как отдельный класс
public class HttpPutData extends Thread {
private final String url;
private final String method;
String result_data = "Empty";
final String[] data;
final String[] field;
// Initialize the spannable string builders.
final SpannableStringBuilder requestHeadersBuilder = new SpannableStringBuilder();
public HttpPutData(String url, String method, String[] field, String[] data) {
this.url = url;
this.method = method;
this.data = new String[data.length];
this.field = new String[field.length];
System.arraycopy(field, 0, this.field, 0, field.length);
System.arraycopy(data, 0, this.data, 0, data.length);
}
@Override
public void run() {
try {
String UTF8 = "UTF-8", iso = "iso-8859-1";
URL url = new URL(this.url);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod(this.method);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
String userAgent = "Mozilla/5.0 (Linux; Android;") AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Mobile Safari/537.36";
// Set the `User-Agent` header property.
httpUrlConnection.setRequestProperty("User-Agent", userAgent);
// Add the `User-Agent` header to the string builder and format the text.
requestHeadersBuilder.append(System.getProperty("line.separator"));
requestHeadersBuilder.append("User-Agent", new StyleSpan(Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
requestHeadersBuilder.append(": ");
requestHeadersBuilder.append(userAgent);
// send Accept-Language
String localeString = Locale.getDefault().toString();
// Set the `Accept-Language` header property.
httpUrlConnection.setRequestProperty("Accept-Language", localeString);
// Add the `Accept-Language` header to the string builder and format the text.
requestHeadersBuilder.append(System.getProperty("line.separator"));
requestHeadersBuilder.append("Accept-Language", new StyleSpan(Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
requestHeadersBuilder.append(": ");
requestHeadersBuilder.append(localeString);
// Get the cookies for the current domain.
String cookiesString = CookieManager.getInstance().getCookie(url.toString());
// Only process the cookies if they are not null.
if (cookiesString != null) {
// Add the cookies to the header property.
httpUrlConnection.setRequestProperty("Cookie", cookiesString);
// Add the cookie header to the string builder and format the text.
requestHeadersBuilder.append(System.getProperty("line.separator"));
requestHeadersBuilder.append("Cookie", new StyleSpan(Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
requestHeadersBuilder.append(": ");
requestHeadersBuilder.append(cookiesString);
}
OutputStream outputStream = httpUrlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, UTF8));
StringBuilder post_data = new StringBuilder();
for (int i = 0; i < this.field.length; i++) {
post_data.append(URLEncoder.encode(this.field[i], "UTF-8")).append("=").append(URLEncoder.encode(this.data[i], UTF8)).append("&");
}
bufferedWriter.write(post_data.toString());
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpUrlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, iso));
StringBuilder result = new StringBuilder();
String result_line;
while ((result_line = bufferedReader.readLine()) != null) {
result.append(result_line);
}
bufferedReader.close();
inputStream.close();
httpUrlConnection.disconnect();
setData(result.toString());
} catch (IOException e) {
setData(e.toString());
}
}
public boolean startPut() {
HttpPutData.this.start();
return true;
}
public boolean onComplete() {
while (true) {
if (!this.isAlive()) {
return true;
}
}
}
public String getResult() {
return this.getData();
}
public void setData(String result_data) {
this.result_data = result_data;
}
public String getData() {
return result_data;
}
}
затем на ваш Activity или Fragment вызовите это код
Handler handler = new Handler();
handler.post(() -> {
// count and key
String[] field = new String[2]; // list with key
field[0] = "key1"; //index and key
field[1] = "key2"; //index and key
//Creating array for data
String[] data = new String[2]; // list with data
data[0] = "value1"; // index and value
data[1] = "value2"; // index and value
HttpPutData httpPutData = new HttpPutData("http://url.com/main.php", "POST", field, data); // link, method, arrayKey, arrayValue;
if (httpPutData.startPut()) {
if (httpPutData.onComplete()) {
String result = httpPutData.getResult();
if(result != null){
Log.i("HttpPutData", result);
}
}
}
}); // end handler
не забудьте добавить разрешения на использование интернета в manifest!
весь данные будет отправлено в виде массива, на страница main.php где вы можете легко обрабатывать с помощью php.